1

これはおそらく非常に単純なことですが、いわばタグですべての製品を取得する最適な方法を探しています。これはSpreeの場合なので、データをモデル化した方法に固執する必要があります。それは実際にProductそしてTaxon(カテゴリー、ブランドなどのように)

では、製品と分類群の場合has_and_belongs_to_many :taxons、分類has_and_belongs_to_many :products群ですべての製品を見つけるための最良の方法は何ですか?

何かのようなもの:

@taxon = Taxon.find_by_permalink('categories/')
@products = Product.find_by_taxon(@taxon)

...しかし、その最後のメソッドに何が入るのかわかりません(名前を作っただけです)。

4

5 に答える 5

2

おそらく、分類群が1つしかない場合は単に言うだけです

@products = @taxon.products

複数ある場合は、少し異なる方法が必要です。しかし、それでもあなたはただ

@products = @taxons.inject([]) {|taxon| taxon.products}
于 2010-01-14T00:10:00.207 に答える
2
@taxon = Taxon.find_by_permalink('categories', :include => :products) 

これにより、製品が熱心にロードされるため、次の方法でアクセスできます

@taxon.products

データベースに再度ヒットすることなく。これは、N+1 クエリの問題を回避する .products を使用するより効率的な形式です。

于 2010-01-14T00:19:22.190 に答える
0

Taxon.find_by_permalink('categories/').products十分ではないですか?

編集:ああ、複数の分類群については、次のようなものを試すことができます:

Product.find(:all, :include => :products_taxons, :conditions => { :products_taxons => {:taxon_id => [1,2,3]} }) # will find products with taxons with id 1, 2 or 3
于 2010-01-14T00:09:10.527 に答える
0

以下のカスタマイズにより、Spree 2.1.0.beta でこれを機能させることができました。

ここの回答に基づいて: Finding records with two specific records in another table

/app/models/spree/product_decorator.rb に新しい製品スコープを追加しました

Spree::Product.class_eval do
  add_search_scope :in_all_taxons do |*taxons|
    taxons = get_taxons(taxons)
    id = arel_table[:id]
    joins(:taxons).where(spree_taxons: { id: taxons }).group(id).having(id.count.eq(taxons.size))
  end
end

次に、新しいスコープを /app/models/spree/base_decorator.rb に追加して使用しました

Spree::Core::Search::Base.class_eval do
    def get_base_scope
      base_scope = Spree::Product.active
      base_scope = base_scope.in_all_taxons(taxon) unless taxon.blank?
      base_scope = get_products_conditions_for(base_scope, keywords)
      base_scope = add_search_scopes(base_scope)
      base_scope
    end
end

これで、標準の検索ヘルパーを使用して製品を取得できるようになりました (つまり、複数の分類群と共にキーワードなどを指定できます)。

# taxon_ids is an array of taxon ids
@searcher = build_searcher(params.merge(:taxon => taxon_ids))
@products = @searcher.retrieve_products

これは私にとってはうまくいき、かなり痛みがなくなりました。しかし、私はより良い選択肢を受け入れています。

于 2013-08-08T06:33:52.770 に答える
0

タグで製品を検索したい場合は、使用できますtagged_with

Spree::Product.tagged_with("example")

タグ「example」が付いた商品を返品します

ソース: https://github.com/mbleigh/acts-as-taggable-on

于 2017-01-25T02:46:13.343 に答える