I want to get possibility to select several Categories for one Post with multiple select.
I have next models: Post, Category and PostCategory.
class
Final solution to organize categories in your posts, I hope it will be useful.
To use multiple we need select_tag:
<%= select_tag "categories", options_from_collection_for_select(Categories.all, 'id', 'name'), :multiple => true %>
Or f.select (many thanks to Tigraine and Brent!), it's more elegant way:
<%= f.select :categories, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %>
In create action of our controller we need:
def create
@post = Post.new(params[:post])
if @post.save
params[:categories].each do |categories|
categories = PostCategory.new(:category_id => categories, :post_id => @post.id)
if categories.valid?
categories.save
else
@errors += categories.errors
end
end
redirect_to root_url, :notice => "Bingo!"
else
render "new"
end
end