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

在我的应用程序中,用户描述建筑物用户应该能够使用分组选择来指定建筑物存在于哪个邻域中.模型看起来像:

class Building
  include Mongoid::Document
  belongs_to :neighborhood
end

class Neighborhood
  include Mongoid::Document
  field :name,type: String,default: nil
  field :borough,default: nil
  field :city,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 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,collection: Neighborhood.grouped_by_borough(city),group_method: :last,option_key_method: :name,option_value_method: :id

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

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...