How to save the has_many association in a database?

I have a User table and a Categories table .

The relationship between these two tables:

  • user has_many :categories
  • category belongs_to :user

I would like to display on the user (standard) edit page a list of categories with checkboxes. When this user will check some of the checkboxes, I would like to save them and then display as noted when he opens the page next time.

But how to display checkboxes in a view? And how to store information about which flags are checked by the user in the database? My first idea was to create a table of type user_categories with user_idand category_id, but not sure how effective this approach is.

What is the best way to accomplish this task now?

+4
source share
3 answers

, . - has_and_belongs_to_many has_many :through, . , , , {user: {category_ids => [1,2,3]}.

class User < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

def update
  current_user.update(user_params)
end

def user_params
  params[:user].permit(
    {:category_ids => []}
  )
end
+3

habtm.

,

 <div class="field"> 
   <%= f.label "Categories" %><br /> 
   <% for category in Category.all %> 
   <%= check_box_tag 'user[category_ids][]', category.id, 
  @user.category_ids.include?(category.id), :id => dom_id(category) %> 
   <%= label_tag dom_id(category), category.name, :class => "check_box_label" %> 
   <% end %> 
 </div>

category.name - .

.

<% @users.each do |user| %>
<%= user.categories.collect(&:name).join(",") %>
<% end %>

. : category_ids attr_acessable.

+2

You probably want to implement a many-many relationship by using has_many :through, rather than belonging to categories, a user (meaning that a category can have only one user, is that what you want?

Read has_many: through to get started. Once you do, checkboxes are easily implemented using the collection_check_boxes helper.

+1
source

All Articles