0

I'm trying to figure out how to construct a collection_select to include two relationships. Here are my models:

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

When I create a new company I use the following to show a select box based on the relationship.

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

But for the departments I'd like to have a select which let's the user select it's company from a select which also includes the companies country, formatted in the following way:

Company 1 - Country 1 Company 2 - Country 1

If i use the following I will only get a list of all the companies which I'd like to be able to see from the list which country they are from.

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

Is there a way for rails to pull the information for the country into a select and append the entry with it's parent country?

I hope I've worded this question correctly! Sorry if it isn't clear.

2 Answers 2

2

Even if @jvnil solution works, I think you should avoid putting this logic in your view. Instead, you could create an instance method in your Company model and use it in your select.

In your model :

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

And in your view :

<%= collection_select(:department, :company_id, Company.all, :id, :name_for_select %>
1
  • This is great thank you siekfired! I'm very new to rails, but you solution really helps me learn as well!
    – calabi
    Feb 2, 2013 at 18:33
1

Use

UPDATE: move logic code to model

# 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

UPDATE: faster version because it only uses needed columns

# 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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.