Rails3多选表单和数据库字段

时间:2012-07-31 15:15:55

标签: ruby-on-rails-3 forms associations multi-select

我有一个应用程序,我正在模型上进行collection_select。我需要能够从SpecialEquipment中选择多个ID。

这是我的选择声明:

<%= f.collection_select(:special_equipment_id, SpecialEquipment.all, :id, :name,  {}, {:multiple => true, :class => 'select'})%>

我正在使用select2 gem来使UI更具吸引力,它允许我选择多个id但是当表单写入数据库时​​它只会写入第一个选择。

1.9.3p194 :004 > Call.last.special_equipment
  Call Load (0.9ms)  SELECT "calls".* FROM "calls" ORDER BY "calls"."id" DESC LIMIT 1
  SpecialEquipment Load (0.3ms)  SELECT "special_equipments".* FROM "special_equipments" WHERE "special_equipments"."id" = 1 LIMIT 1
 => #<SpecialEquipment id: 1, name: "O2", created_at: "2012-06-27 21:43:41", updated_at: "2012-06-27 21:43:41"> 

我做错了什么?我的关联设置如下:

Call.rb belongs_to:special_equipment

Special_Equipment.rb  has_many:调用

1 个答案:

答案 0 :(得分:0)

这是通过使用has_many:通过关联并将表单输入写入连接表来解决的。我现在能够多选并正确保存记录。