表格不保存多个ID

时间:2013-08-06 09:38:13

标签: ruby ruby-on-rails-3 forms

我有以下

class Portfolio < ActiveRecord::Base
belongs_to :sector

attr_accessible :overview, :title, :sector_id

end

class Sector < ActiveRecord::Base
has_many :portfolios
attr_accessible :name
end 

我的表单中有一个collection_select用于创建新的投资组合

<%= f.collection_select(:sector_id, Sector.all, :id, :name, {:prompt => "Please Select a Sector"}, {:multiple => true}) %>

当我提交表单时,它会保存所有其他属性,但不会传递或保存sector_id。

我希望能够为扇区参数保存多个ID

我能错过什么?

我是否需要在我的投资组合模型中使用accepts_nested_attributes_for:sector?

1 个答案:

答案 0 :(得分:1)

您的案例中的推荐用法:

portofolio模型

class Portofolio < ActiveRecord::Base
  attr_accessible :sector_ids, ....
  has_many :portofolio_sectors
  has_many :sectors, through: :portofolio_sectors
end

格式

<%= f.collection_select :sector_ids, Sector.order(:name), :id, :name, {:prompt => "Please Select a Sector"}, {multiple:true} %>

portofolio_sectors模型

class PortofolioSector < ActiveRecord::Base
  belongs_to :portofolio
  belongs_to :sector
end

行业模式

class Sector < ActiveRecord::Base
  has_many :portofolio_sectors
  has_many :portofolios, through: :portofolio_sectors
end

http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

这对您来说可能很有意思,必须有专业帐号:

http://railscasts.com/episodes/258-token-fields-revised

<强>更新

当您使用sectorsportofolio添加multiple select时,sector_ids将填充array属于Sector的ID },并且在提交栏上会读取param[:sector_ids]这个[2,5,17,8],并且会portofolio_sectors创建4个(在这种情况下为4个)sector_id = 2, 5, 17, 8个记录,每个那些porofolio_id将是当前portofolio.id,例如:2。结果你将拥有:

portofolio_sectors表:

id   portofolio_id     sector_id
 1               2             2
 2               2             5
 3               2            17
 4               2             8

如何从sector_ids创建portofolio_sectors您还可以看到此链接:http://railscasts.com/episodes/382-tagging,请参阅tag_lis方法。

在视图中,您可以使用portofolio.sectors访问行业,这将是属于此array的{​​{1}} sectors