Martin
Martin

Reputation: 11336

collection_select using value from nested association

I have a select field with a collection of all Address. I want to show something like "address.name / country.name" as value.

= item.collection_select :address_id, Address.all, :id, :name

Currently in this sample, I'm only showing address.name attribute. How can I nest other values here and how can I call a value from a nested association? (address.country.name). ?

I got it working by doing something like this. Just wondering if there is something better.

%select{name: "user[address_id]"}
  - Address.all.each do |address|
    %option{value: address.id}
      = address.name
      = address.country.name

Upvotes: 2

Views: 461

Answers (2)

Rails Guy
Rails Guy

Reputation: 3866

Try this out :

= item.collection_select :country_id, Address.all, :id, :full_address

Than add a method to your model :

def full_address
   full_address = name
   full_address += " / #{country.name}" if country.present?
   full_address
 end

Upvotes: 1

MrYoshiji
MrYoshiji

Reputation: 54882

You can write your own method on the Address model that will return a nice name for the collection select:

class Address < ActiveRecord::Base

  def name_with_country
    str = self.name
    str += " #{self.country.name}" if self.country.present?
    str
  end

And use it in the collection_select:

= item.collection_select :address_id, Address.all, :id, :name_with_country

Upvotes: 3

Related Questions