I want to get possibility to select several Categories for one Post with multiple select.
I have next models: Post, Category and PostCategory.
class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, :through => :post_categories
end
class Category < ActiveRecord::Base
has_many :post_categories
has_many :posts, :through => :post_categories
end
class PostCategory < ActiveRecord::Base
has_one :post
has_one :category
belongs_to :post # foreign key - post_id
belongs_to :category # foreign key - category_id
end
In my controller I have something like @post = Post.new .
I’ve created some categories.
And in view I have:
<%= form_for @post do |f| %>
<%= f.text_field :title %>
<%= f.select :categories, :multiple => true %>
<%= f.submit %>
<% end %>
And… where is my categories? I have only “multiple” in select options. I think it’s something wrong with my form.
Sorry to resurrect the dead, but I found a much simpler solution that lets one use the default controller action code and use the ActiveModel setter logic for a has_many. Yes, it’s totally magic.
Specifically, using the :category_ids (or :your_collection_ids) param name will automagically tell Rails to call
@post.category_ids = params[:post][:category_ids]to set the categories for that post accordingly, all without modifying the default controller/scaffold #create and #update code.Oh, and it works with
has_many :something, through: :something_elseautomatically managing the join model. Freaking awesome.So from the OP, just change the field/param name to
:category_idsinstead of:categories.This will also automatically have the model’s selected categories populate the select field as highlighted when on an edit form.
References:
From the has_many API docs where I found this.
Also the warning from the form helpers guide explains this “type mismatch” when not using the proper form-field/parameter name.
By using the proper form-field/param name, you can dry up new and edit forms and keep the controllers thin, as encouraged by the Rails way.
note for rails 4 and strong parameters: