在rails 4中动态设置groups_collection_select中的数据属性

时间:2013-10-08 18:31:52

标签: ruby-on-rails ruby-on-rails-4

我的订单/新页面中有这样的表格。我用它来选择模型位置,然后根据上面选择框中选择的内容从位置中选择一个模型。

<%= f.label "SELECT MODEL LOCATION *" %>
          <div class="list_number">1</div><%= f.collection_select :location_id, Location.all, :id, :formatted_display, prompt: true, :required => true,  :class => 'chosen-select' %>

          <%= f.label "SELECT YOUR MODEL *" %>
          <div class="list_number">2</div>
          <%= f.grouped_collection_select :performer_id, Location.order(:name).map{|group| Performer.find_by_location_id(group.id).map{|performer| {'data-markup'=>performer.white_label.markup}}}, :performers, :name, :id, :first_name, include_blank: true, :required => true,  class: 'chosen-select' %>

当我使用map设置数据属性时,在grouped_collection_select中,我收到以下错误:

undefined method `map' for #<Performer:0x00000006813958>

如何解决此错误并获取所需数据?


尝试以下代码后

<%= f.grouped_collection_select :performer_id, Location.order(:name).map{|group| Performer.where(location_id: group.id).map{|performer| {'data-markup'=>performer.white_label.markup}}}, :performers, :name, :id, :first_name, include_blank: true, :required => true,  class: 'chosen-select' %>

我收到以下错误

undefined method `performers' for [{"data-markup"=>#<BigDecimal:67e80c8,'0.0',9(36)>}]:Array

当我尝试以下

<%= f.grouped_collection_select :performer_id, Location.order(:name), :performers, :name, :id, :first_name,Location.order(:name).map{|group| Performer.where(location_id: group.id).map{|performer| {'data-markup'=>performer.white_label.markup}}}, include_blank: true, :required => true,  class: 'chosen-select' %>

我收到以下错误

undefined method `merge' for #<Array:0x000000069705a8>

1 个答案:

答案 0 :(得分:0)

Performer.find_by_location_id(group.id)

返回一个实例,但map是Array的方法。 修复取决于您的业务逻辑(和APP结构) 如果有很多表演者

,您可以使用Performer.where(location_id: group.id).map...

我认为你试图错误地使用这个助手。根据{{​​3}},您应该传递collectiongroup_methodgroup_method - The name of a method which, when called on a member of collection, returns an array of child objects representing the <option> tags.

您将对象数组[{'data-markup' => some_value}, ...]作为集合传递,将performers作为group_method传递。 Rails尝试调用{'data-markup' => some_value}.performers,这会引发异常。

您应该按以下方式重写集合: 1.它应该是数组 2.每个数组项都应该有方法performers - 它返回一个组项目下的对象数组

我希望它能帮到你

我无法测试,但它可以工作(如果位置has_many表演者或你可以根据你的业务逻辑实现自己的方法)

<%= f.grouped_collection_select :performer_id, Location.order(:name), :performers, :name, :id, :first_name, include_blank: true, :required => true,  class: 'chosen-select' %>