jeudi 30 juillet 2015

Assign Subcategories to a Main Category

On my current local blog site I'm able to create both Categories and Subcategories.

I want to make is so when creating a post, once you choose the category from the drop-down, it will only show the available subcategories.

Example:

enter image description here

In this example "News is selected". So I need to do two things. First, assign the subcategories I make to specific categories. Second, display the subcategories accordingly depending on which category is chosen.

Post Model

class Post < ActiveRecord::Base
  belongs_to :category
  belongs_to :subcategory
  has_many :comments

end

New Post View

<h2>Add New Post</h2>

<div class="well">
<%= form_for [:admin, @post] do |f| %>

    <div class="form-group">
        <%= f.label :title %>
        <%= f.text_field :title ,class:'form-control' %>
    </div>

    <div class="form-group">
        <%= f.label :category %>
        <%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, {:include_blank => 'Select One'},class:'form-control' %>
    </div>

    <div class="form-group">
        <%= f.label :image %>
        <%= f.file_field :image %>  
    </div>
    <br>

    <div class="form-group">
        <%= f.label :subcategory %>
        <%= f.select :subcategory_id, Subcategory.all.collect {|x| [x.name, x.id]}, {:include_blank => 'Select One'},class:'form-control' %>
    </div>

    <div class="form-group">
        <%= f.label :body %>
        <%= f.text_area :body ,class:'form-control', id:'eg-textarea' %>
    </div>
    <br>
    <%= f.submit "Submit", class:'btn btn-primary' %>
    <%=link_to "Cancel", admin_posts_path, class:'btn btn-default' %>
<% end %>
</div>

Posts Controller

class Admin::PostsController < Admin::ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    @post.save
    redirect_to admin_posts_path
  end

  def edit
  end

  def update
  end

  def index
    @posts = Post.all
  end

  def show
  end

  def destroy
  end

  private
    def post_params
      params.require(:post).permit(:title, :category_id, :subcategory_id, :image, :body)
    end
end

Aucun commentaire:

Enregistrer un commentaire