rails:使用关联模型的列:where

时间:2012-04-10 22:26:49

标签: ruby-on-rails ruby-on-rails-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)

这里有什么问题?

1 个答案:

答案 0 :(得分:3)

includes方法并不完全符合您的想法。将joins替换为includes,它应该做你的意思:

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查询中转换为JOIN,因此您可以在已连接的表上执行WHERE子句。 include只是要求Active Record执行另一个查询以选择给定表中的所有相关记录。如果你们同时进行这两项操作,Active Record会创建一个(相当长的)多功能一体机,它们都连接两个表并使用结果来创建两组对象。