2013-02-26 93 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属性为您的选择

=显示属性为您的选择