微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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大师有一个更清洁的方式处理这个,我很想听听它.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐