3

ここで何が起こっているのかわかりません。私は自分の関連付けで動作する作成しようとしているスコープを持っています:

class Subscription < ActiveRecord::Base
  belongs_to :subscriber, :class_name => "User"
  belongs_to :subscribable, :polymorphic => true
end

create_table :products do |t|
   t.string  :name
   t.decimal :price
   t.decimal :cost_per_unit
   t.integer :user_id
end

create_table :subscriptions do |t|
   t.string  :name
   t.decimal :price
   t.decimal :cost_per_unit
   t.integer :subscriber_id
   t.integer :subscribable_id
   t.string  :subscribable_type
end

class Product < ActiveRecord::Base
  has_many :subscriptions, :as => :subscribable, :dependent => :destroy

  def self.lower_prices
      Product.includes(:subscriptions).
      where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit" )
  end
end

製品の低価格とサブスクリプションを比較しようとしていますが、次のエラーが表示されます。

ActiveRecord::StatementInvalid in Pages#subscribed_products

PGError: ERROR:  missing FROM-clause entry for table "subscriptions"
LINE 1: ...  WHERE (user_id != 2) AND (products.price < subscripti...
                                                             ^
: SELECT COUNT(*) FROM "products"  WHERE (user_id != 2) AND (products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit)

ここで何が問題なのですか?

4

1 に答える 1

3

このincludes方法は、あなたが考えていることとまったく同じではありません。代わりjoinsincludes、あなたが意味することを行う必要があります:

Product.joins(:subscriptions).
      where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit" )

多分:

Product.includes(:subscriptions).joins(:subscriptions).
      where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit" )

joinsは、結果の SQL クエリでa に変換されるJOINため、結合されたテーブルで WHERE 句を実行できます。 include指定されたテーブル内のすべての関連レコードを選択するために別のクエリを実行するよう Active Record に要求するだけです。両方を一緒に行うと、Active Record は 2 つのテーブルを結合し、結果を使用してオブジェクトの両方のセットを作成する (かなり長い) オールインワンを作成します。

于 2012-04-11T01:46:19.907 に答える