当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – simple_form分组选择关联给出“未定义的方法`map’”

来源:互联网 收集:自由互联 发布时间:2021-06-23
在我的应用程序中,用户描述建筑物用户应该能够使用分组选择来指定建筑物存在于哪个邻域中.模型看起来像: class Building include Mongoid::Document belongs_to :neighborhoodendclass Neighborhood includ
在我的应用程序中,用户描述建筑物用户应该能够使用分组选择来指定建筑物存在于哪个邻域中.模型看起来像:

class Building
  include Mongoid::Document
  belongs_to :neighborhood
end

class Neighborhood
  include Mongoid::Document
  field :name,         type: String, default: nil
  field :borough,      type: String, default: nil
  field :city,         type: String, default: nil
end

使用simple_form,我试图生成一个分组选择表示建筑物可能属于的邻域列表.

= building_form.association :neighborhood, as: :grouped_select, collection: Neighborhood.where(city: city), group_method: :borough

理想情况下,这样可以创建:

Borough #1
  Downtown
  Uptown
Borough #2
  Suburbs
  ...

但是,我收到此错误:

undefined method `map' for "Borough #1":String

看起来它正在调用Neighborhood.borough.map,并且因为String没有map函数,所以它会出错.我该如何解决?

我已经在这个问题上挣扎了一段时间,不幸的是,我希望通过联想得到的直观的“Rails”魔法似乎并不存在.它正在使用底层的Railsroup_collection_select,它似乎不能很好地处理对象/模型.

相反,它似乎更好地处理数组.根据this documentation,收集输入应采用以下形式:

[
  ['group_name',
    [
      ['item-name','item-value'],
      ['item2-name','item2-value'],
      ...(more items)...
    ]
  ],
  ['group2_name',
    [
      ['item3-name','item3-value'],
      ['item4-name','item4-value'],
      ...(more items)...
    ]
  ],
  ...(more groups)...
]

MongoDB模型自然不适合这种格式,所以我在我的Neighborhood类上写了一个helper方法:

def self.grouped_by_borough(city)
  groups = []
  Neighborhood.where(city: city).distinct(:borough).each_with_index do |borough, index|
    groups << [borough, Neighborhood.where(city: city, borough: borough)]
  end
  return groups
end

然后我的协会看起来像:

= building_form.association :neighborhood, as: :grouped_select, collection: Neighborhood.grouped_by_borough(city), group_method: :last, option_key_method: :name, option_value_method: :id

这也会自动选择任何先前选择的邻域,这便于“编辑”表单.

如果任何Rails形式/ Mongoid大师有一个更清洁的方式处理这个,我很想听听它.

网友评论