1

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).

at.
  • 50,922
  • 104
  • 292
  • 461
  • meaning that for Eg: game category can have option 1 and 2 value, when it submit or edit, the db will have 2 records which value 1 and 2? – Nich Nov 21 '12 at 01:40
  • @Nich - yes, I think. If you choose both categories for a game, the database will have 2 records in the `categories_games` join table. – at. Nov 21 '12 at 02:29
  • Take a look at this: http://stackoverflow.com/questions/1847641/trying-to-use-accepts-nested-attributes-for-and-has-and-belongs-to-many-but-the – MrYoshiji Nov 21 '12 at 02:59

0 Answers0