I have 2 models:
class Game < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :games
end
I want to have an HTML multiple select in _form.html.erb
that generates something like this:
<select id="game_category_id" name="game[category_id]" multiple="multiple">
<option value="1">First Person Shooter</option>
<option value="2">Role Playing Game</option>
</select>
When submitting the form to create a new game
or edit a game
, the categories selected should be saved accordingly. I typically use Rails' collection_select
method for select
fields. Can I use that for multiple selects as well?
<%= f.collection_select(:category_id, Category.order('name'), :id, :name, {include_blank: true}) %>
One issue is, of course, I don't have a category_id
field in the game
model. It's a collection of categories
. I'm using the latest stable Rails (3.2.9 at the moment).