0

次のモデル クラスがあります。

class OptionCategory < ActiveRecord::Base
  attr_accessible :disabled, :list_index, :name
  has_many :options
end


class Option < ActiveRecord::Base
  attr_accessible :disabled, :name, :option_category_id
  belongs_to :option_category
  has_and_belongs_to_many :products
end


class Product < ActiveRecord::Base
  attr_accessible :annual_fee, :bal_transfer_intro_apr_end, :bal_transfer_intro_apr_start, :balance_transfer_fee, :description, :image, :image_cache, :name, :pur_intro_apr_end, :pur_intro_apr_start, :sign_up_bonus, :sign_up_bonus_type, :url
  mount_uploader :image, ImageUploader

  has_and_belongs_to_many :options
end

私のコントローラーの 1 つで、オプション ID の配列を受け取りました。これらの ID に一致するオプションを持つ製品を照会したいと思います。Railsでこれを行う簡単な方法はありますか? ありがとう!

4

2 に答える 2

1

次を使用して、すべてのオプションを見つけて N+1 を最適化できますincludes

Option.includes(:products).where(:id => array_of_ids)

これにより、オプションの読み込み、フィールドのselect * from options where id in [array_of_ids]抽出、追加のクエリが 1 回実行されます。product_idselect * from products where id in [product_ids]

has_many :throughを使用して、結合テーブルをラップするモデルを作成することで、これを自分で簡単に行うことができます。このモデルを と呼ぶとProductOptions、次のように簡単に実行できます。

Product.find(ProductOptions.where(:option_id => array_of_option_ids).map(&:product_id).uniq)
于 2012-08-20T21:03:52.003 に答える
0
Product.joins(:options).where(:options => {:id => params[:options]}).group(:id)
于 2012-08-21T17:37:03.793 に答える