Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1checkboxform-helpers

How to get model objects in the form with rails check_box?


How do i get checkbox values in the form from the database? I want the form to bring the existing sub category name,and when i check the checkbox to select that particular category name and not create a new one.I have tried ryan bate's railscast but was no help to me. The realationship here is Category has_many SubCategories and SubCategory belongs_to Category.Thank you.

 <%= form_for @category ,:url=>{:action =>"create"} do |f| %>
 <%=f.text_field :category_name %>
 <%= f.fields_for :sub_categories do |s| %>
 <% @category.sub_categories.each do |sub|%>
 <%=s.check_box "name",{},sub.id %>  <!--need help here-->
 <%end%> 
 <%end%>
 <%=f.submit "submit"%>
 <%end%>

Solution

  • Based on the exchange in the comments, it appears that you want to use the checkboxes to assign SubCategory objects to a Category object. If that's the case, you're association should be that a Category has_and_belongs_to_many :sub_categories. Then your form would look something like:

    <%= form_for @category ,:url=>{:action =>"create"} do |f| %>
     <%=f.text_field :category_name %>
     <% SubCategories.each do |sc| %>
        <div>
          <%= check_box_tag :sub_category_ids, sub_category_id, @category.sub_categories.include?(sc), :name => 'category[sub_category_ids][]' -%>
          <%= label_tag :sub_category_ids, sc.name -%>
        </div>
      <% end -%>
    <% end %>
    

    Which will show a category form and then list all of the sub_categories that can be assigned or unassigned by checking the checkboxes.

    You will also need a join table "categories_sub_categories" for this new association and logic (likely in your controller) to handle the actual assignment.

    example for your category_controller.rb

    def create
        @category = Category.find(params[:id])
        #use the checked sub_category_ids from the form to find and assign the sub_categories.
        assigned_sub_categories = SubCategory.find(params[:category][:sub_category_ids]) rescue []
        @category.sub_categories = assigned_sub_categories
        if @category.save
          …
        else
          …
        end
    end