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.