2013-02-26 84 views
1

我試圖使用collection_select顯示下拉列表。但是,在搜索了一段時間之後,我仍然無法理解如何設置此方法的參數。rails:需要對collection_select的一些解釋

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 

我想顯示名爲「地址類型」從模型「地址類型」 每個地址選擇的下拉列表。 「AddressType」的唯一值是在「seeds.rb」中創建的「Home」,「Work」和「Other」。這裏是_form代碼:

.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 

我不知道如何設置collection_select的參數,所以我的line'5'肯定是錯誤的。其他文檔和示例如此混亂,所以任何人都可以解釋如何使用collection_select進行操作?

回答

1

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

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

當您使用form.collection_select,你應該忽略對象,例如

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

感謝您的幫助。我可以更好地理解collection_select發生了什麼,它的工作原理。 – 2013-02-26 17:12:30

+0

我有一個後續問題,當我點擊我的新地址頁面上的「創建」按鈕後,addresstype就會出現錯誤,說明未知的屬性:類型,但我肯定將它包含在它的模型中? – 2013-02-26 17:15:03

1

請確保您收到的地址類型沒有問題。

使用以下命令:

@addresses = AddressType.all 


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

其中,

地址類型 =你的模型,

=型號字段名,

@addresses =收藏包含'H青梅」,‘工作’和‘從地址類型表中的其他’,

ID = value屬性爲您的選擇

=顯示屬性爲您的選擇