There are 2 classes

class Post < ActiveRecord::Base has_and_belongs_to_many :tags end class Tag < ActiveRecord::Base has_and_belongs_to_many :posts end 

When creating a post, I print the list of tags in the form of checkboxes:

 <% Tag.all.each do |tag| %> <%= f.check_box :tags, {multiple: true}, tag.id, nil %> <%= tag.title %> <% end %> 

On the controller comes:

 "tags"=>["19", "26"] 

Now I don’t understand how to create corresponding records in the PostTags link table?

    1 answer 1

    In this case, do not need a multi-model form. The rails out of the box have magic for this. But you need to use not tags but tag_ids .

     post = Post.last post.tag_ids = Tag.ids 

    As a result, all tags existing in the database will be added to the last post. In the intermediate table records will be created automatically.

    At the same time, there is sugar for such checkboxes too:

     <%= f.collection_check_boxes, :tags_ids, Tag.all, :id, :title %> 

    UPD:

     <% Tag.all.each do |tag| %> <%= f.check_box :tags, {multiple: true}, tag.id, nil %> <%= tag.title %> <% end %> 

    This cycle has a significant disadvantage. Because in unchecked_value nil is passed - hiddens will not be added, and if you reset all checkboxes, the parameter will simply be ignored. If you leave the default value (0), or explicitly set an empty string, for example, then this value will be transferred instead of each unselected checkbox. The second is not scary, just sloppy. So it is better to use collection_check_boxes which will add only one empty hideden.

    • I somehow ran into a funny bug, you might want to check and reflect it in your response: if you don’t select one , an empty array will come to the server, but on the way to the controller it will turn into nil , which is why the assignment nil will not erase all associations , but ignore changes . This is only repaired in Rails 5, it has not been released yet. - D-side
    • @ D-side, hmm. I have never come across this. At first glance it looks like a strong params glitch or problems with form-helpers. Have any links? I would study the question. - anoam
    • Hehe. Yes, I thought so too. But no, this is not just a bug, it is a feature (I know, I know), which appeared as a fix for some vulnerability in Rails 3.2 (yes, so long ago!). There are a lot of tickets about this, quite a bright one , and here's a ticket about the repair process . - D-side
    • @D-side, as I understand it, this is true for json requests. Yes, and collection_check_boxes defaults to adding hidden with the value "". Yes, and post.tag_ids = nil will cause all entries to be deleted from the staging table. - anoam
    • one
      @Pavel, are the parameters exactly right? tag_ids is an array and you need something like param.require(:post).permit(:title, :text, :category_id, tag_ids: []) . - anoam