此代码
new_hash = [{:id=>1,:name_t=>"Y/N"},{:id=>2,:name_t=>'Number'},{:id=>3,:name_t=>'Text'}]
collection_select(:question,:q_type, new_hash ,:id,:name_t )
正在抛出错误
undefined method ``name_t' for {:id=>1, :name_t=>"Y/N"}:Hash
让我发疯了
更新
我正在尝试向表单添加DRY静态下拉菜单
= form_for @question do |f|
- if @question.errors.any?
#error_explanation
%h2= "#{pluralize(@question.errors.count, "error")} prohibited this question from being saved:"
%ul
- @question.errors.full_messages.each do |msg|
%li= msg
.row{:style=>"margin-bottom: 5px"}
.col-xs-2
= f.label :pm_type
.col-xs-2
= f.collection_select(:pm_type_id, PmType.all.where(:is_active => true), :id, :name)
.row{:style=>"margin-bottom: 5px"}
.col-xs-2
= f.label :proposition
.col-xs-2
= f.text_field :proposition
.row{:style=>"margin-bottom: 5px"}
.col-xs-2
= f.label "Type"
.col-xs-2
-# ######## Code goes here ##########
- new_hash = [{:id=>1,:name_t=>"Y/N"},{:id=>2,:name_t=>'Number'},{:id=>3,:name_t=>'Text'}]
= collection_select(:question,:q_type, new_hash ,:id,:name_t )
.row{:style=>"margin-bottom: 5px"}
.col-xs-2
= f.label "Weight"
.col-xs-2
= f.text_field :q_weight
.row{:style=>"margin-bottom: 5px"}
.col-xs-2
= f.label "Active?"
.col-xs-2
= check_box_tag(:is_active, 1 ,true)
.actions
= f.submit 'Save'
答案 0 :(得分:2)
根据文档here,collection_select
的第五个参数应该是一种方法。
来自api-doc:
:value_method
和:text_method
参数是要在每个集合成员上调用的方法。
由于name_t
是数组中元素的键,因此无法将其用作方法。
但你可以试试这个:
class MyType < Struct.new(:id, :name_t)
end
new_hash = [MyType.new(1,"Y/N"),MyType.new(2,"Number"),MyType.new(2,"Text")]
p new_hash[0].name_t
答案 1 :(得分:0)
感谢您的帮助!我在查看文档时找到了select方法,最后执行了以下操作:
select(:question,:q_type, [["Y/N",1],['Number',2],['Text',3]], {} )