【问题标题】:simple_form grouped select association gives "undefined method `map'"simple_form 分组选择关联给出“未定义的方法 `map'”
【发布时间】:2013-09-19 13:22:48
【问题描述】:

在我的应用程序中,用户描述建筑物。用户应该能够使用分组选择指定建筑物所在的社区。模型如下所示:

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,并且因为字符串没有map 函数,所以它会出错。我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails forms simple-form


    【解决方案1】:

    我为此苦苦挣扎了一段时间,不幸的是,我希望从association 获得的直观“Rails”魔法似乎并不存在。它使用的是底层 Rails grouped_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 类上编写了一个辅助方法:

    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
    

    那么我的association 看起来像:

    = 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 大师有更简洁的方法来处理这个问题,我很想听听。

    【讨论】:

    • 哇,你让我意识到这并不容易。我一直在努力寻找“银弹”,但你的模式对我有用,谢谢!
    • 我不需要option_key_method,也不需要option_value_method
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多