3

私のアプリケーションでは、ユーザーは建物について説明します。ユーザーは、グループ化された選択を使用して、建物が存在する近隣を指定できる必要があります。モデルは次のようになります。

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エラーが発生します。これを修正するにはどうすればよいですか?

4

1 に答える 1

7

私はしばらくこれに苦労してきましたが、残念ながら、私が望んでいた直感的な「Rails」マジックはassociation存在しないようです。grouped_collection_selectオブジェクト/モデルをうまく処理していないように見える基礎となる Rails を使用しています。

代わりに、配列をより適切に処理するように見えます。このドキュメントによると、コレクションの入力は次の形式にする必要があります。

[
  ['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 達人がこれを処理するためのよりクリーンな方法を持っている場合は、それについて聞きたいです。

于 2013-09-15T16:31:15.703 に答える