从轨道3中的2个表中选择f.collection_select

时间:2012-05-19 09:28:03

标签: ruby-on-rails ruby-on-rails-3.1

我已经形成了这个代码行<%= f.collection_select :owner_ids, Owner.order(:id), :id, :name, {}, {multiple: true} %>,它返回了massmedium形式的所有者列表,但我在这个领域也需要包括这些公司,所以我也可以在同一个列表中列出这些公司因为大众传媒可能由个人或公司拥有。

Company.rb

class Company < ActiveRecord::Base

  has_many :ownerships
  has_many :massmedia, through: :ownerships
  has_many :owners, through: :ownerships
end

Owner.rb

class Owner < ActiveRecord::Base

  has_many :ownerships
  has_many :massmedia, through: :ownerships
  has_many :companies, through: :ownerships
end

Massmedium.rb

class Massmedium < ActiveRecord::Base
  belongs_to :category

  has_many :ownerships
  has_many :owners, through: :ownerships
  has_many :companies, through: :ownerships

end

1 个答案:

答案 0 :(得分:0)

= f.select :owners, options_for_select((Owner.all + Company.all)
  .collect{|o| [o.name, "#{o.class},#{o.id}"], {multiple: true}

你必须在你的模型中定义owners=(values)方法,它将解析像[“Company,1”,“Owner,2”]这样的值