有没有一种方法可以让几行通用代码根据模型定义而不是代码行从正确的model_class
返回结果?
现在,我正在使用一个生成器来创建:
<%= f.collection_select(:semanticZoomOut, Class.all.sort { |a,b| a.name <=> b.name },
:id, :name, options = {
:prompt => "Please Select an Item",
:selected => @instance.semanticZoomOut.map(&:id)
}, html_options = {:multiple => true, :class=>"search"}) %>
其中,必须为每个_form.html.erb
手动更改"类别"。最好,我想生成这样的东西:
<%= f.collection_select(:semanticZoomOut, @instance.semanticZoomOut.class.all.sort { |a,b| a.name <=> b.name },
:id, :name, options = {
:prompt => "Please Select an Item",
:selected => @instance.semanticZoomOut.pluck(id)
},
html_options = {:multiple => true, :class=>"search"}) %>
这个怎么样?
clazz = @instance.class.associations[:semanticZoomOut].model_class.to_s.constantize
clazz.all.sort_by(&:name)
或者,如果你想让Cypher做这项工作:
clazz.order(:name)