2013-12-11 67 views
1

如何为模型生成一个选择字段?如何将选择(下拉列表)添加到我生成的表单中?

我的控制器发送应该用来填充选择的数组。

控制器:

def new 
    @categories= Category.all 
    @product= Product.new 
end 

类型模型有一个ID和一个标签。

的形式如下:

=form_for :product do |f| 
- if @product.errors.any? 
#error_explanation 
    %h2 
    = pluralize(@product.errors.count, "error") 
    prohibited 
    this product from being saved: 
    %ul 
    - @product.errors.full_messages.each do |msg| 
     %li= msg 
%p 
    = f.label :title 
    %br 
    = f.text_field :title 
%p 
= f.label :category_id 
%br 
= f.xxxxxxxxx 
%p 
    = f.submit 

xxxxxxxxx是我需要选择由@categories数组填充的地方。

回答

2
= f.select :category_id, @categories.collect {|c| [ c.name, c.id ]} 

其中@categoriesCategory.all

+0

谢谢,现在我明白了。它工作得很好。 – LogofaT

1

我会避免@NARKOZ建议有两个原因。最重要的是它将应该在控制器中的逻辑(获取类别记录)嵌入到视图中。这是不好的分离。其次,有一个非常方便的collection_select方法可以完成同样的事情。

= f.collection_select :category_id, @categories, :id, :name, {prompt: 'Pick a category'}, { class: 'select-this' } 

这假定您已经装入控制器@categories实例变量,你在你的问题了。

请注意,此方法最后需要两个可选哈希。第一个散列接受select方法的通常选项。第二个哈希接受HTML选项(例如HTML样式,类等,属性)。

+0

+1,用于将逻辑视图分离到控制器中。 –

相关问题