Chong Yue
Chong Yue

Reputation: 155

rails: need some explanations of collection_select

I tried to do display a drop-down list using collection_select. However, after searching around for a while I still can't understand how to setup the parameters for this method.

class Entry < ActiveRecord::Base
    has_many :addresses
    attr_accessible :email, :first_name, :last_name
end
class Address < ActiveRecord::Base
    belongs_to :entry
    has_one :address_type
    attr_accessible :type, :city, :state, :street, :zip
end

class AddressType < ActiveRecord::Base
    belongs_to :address
    attr_accessible :name
end

And I want to display a drop-down list named "AddressType" selected from model "AddressType" for each address. The only values of "AddressType" are 'Home', 'Work' and 'Other' which are created in seeds.rb. Here's the _form code:

.form-inputs
  5     = f.collection_select (:AddressType, :name, AddressType.all, :id, :AddressType)           
  6     = f.input :street
  7     = f.input :city
  8     = f.input :state
  9     = f.input :zip

I have no idea how to setup the parameters of collection_select, so my line'5' is definitely wrong. Other Docs and example are so confusing, so can any one explain how can I do it with collection_select?

Upvotes: 1

Views: 699

Answers (2)

sjain
sjain

Reputation: 23354

Make sure the address types you are getting are fine.

Use the following:

@addresses = AddressType.all


f.collection_select ("address_type", "name", @addresses, "id", "name")

where,

AddressType = Your model,

name = Model field name,

@addresses = Collection that contains 'Home', 'Work' and 'Other' from the AddressType table,

id = value attribute for your option

name = display attribute for your option

Upvotes: 1

shweta
shweta

Reputation: 8169

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

= f.collection_select (:type, AddressType.all, :id, :name)

when you use form.collection_select, you should omit object, e.g.

form.collection_select(method, collection, value_method, text_method, options = {}, html_options = {})

Upvotes: 1

Related Questions