0

我试图弄清楚如何构建一个 collection_select 来包含两个关系。这是我的模型:

class Country < ActiveRecord::Base
  has_many :companies, :dependent => :destroy
end

class Company < ActiveRecord::Base
  belongs_to :country
  has_many :departments, :dependent => :destroy
end

class Department < ActiveRecord::Base
  belongs_to :company
end

当我创建一家新公司时,我使用以下内容显示基于关系的选择框。

<%= collection_select(:company, :country_id, Countries.all, :id, :name, :prompt => 'Please select country') %>

但是对于部门,我想要一个选择,让用户从选择中选择它的公司,该选择还包括公司国家,格式如下:

公司 1 - 国家 1 公司 2 - 国家 1

如果我使用以下内容,我只会得到我希望能够从列表中看到它们来自哪个国家的所有公司的列表。

<%= collection_select(:device, :cabinet_id, Cabinet.all, :id, :name, :prompt => 'Please select cabinet') %>

rails 有没有办法将国家/地区的信息拉到一个选择中并将条目附加到它的父国家/地区?

我希望我这个问题的措辞正确!抱歉,如果不清楚。

4

2 回答 2

2

即使@jvnil 解决方案有效,我认为您应该避免将此逻辑放在您的视图中。相反,您可以在Company模型中创建一个实例方法并在您的选择中使用它。

在您的模型中:

class Company< ActiveRecord::Base
  def name_for_select
    name + " - " + country.name
  end
end

在您看来:

<%= collection_select(:department, :company_id, Company.all, :id, :name_for_select %>
于 2013-02-02T14:53:40.500 回答
1

利用

更新:将逻辑代码移动到模型

# company.rb
def company_with_country
  "#{name} - #{country.name}" # this is better than using `string + string` since it creates only 1 string
end

# view
collection_select :department, :company_id, Company.includes(:country).all, :id, :company_with_country

更新:更快的版本,因为它只使用需要的列

# controller
@companies = Company.joins(:country)
  .select('companies.id, companies.name, countries.name AS country_name')
  .map { |c| ["#{c.name} - #{c.country_name}", c.id] }`

# view
select :department, :company_id, @companies
于 2013-02-02T13:07:37.220 回答