0

我有以下

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}) %>

当我提交表单时,它会保存所有其他属性,但没有传递或保存扇区 ID。

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

我能错过什么?

我需要在我的投资组合模型中使用 Accepts_nested_attributes_for :sectors 吗?

4

1 回答 1

1

在您的情况下推荐使用:

投资组合模型

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} %>

portfolio_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

更新

当您添加sectorsportofoliousing时multiple selectsector_ids将填充一个array属于 的 id Sector,并且在提交 rails 将读取param[:sector_ids]如下内容:[2,5,17,8]并将创建 4 个(在本例中为 4 个)portofolio_sectors记录,其中sector_id = 2, 5, 17, 8每个记录porofolio_id将是当前portofolio.id例如: 2. 结果,您将拥有:

投资组合表:

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属于sectorsthis的一个portofolio

于 2013-08-06T11:47:35.683 回答