Rails: using related model columns in: where

I'm not sure what is going on here. I have an area that I'm trying to create that works with my association:

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

I am trying to compare a lower Product price with a subscription, but this gives me an error:

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)

What is wrong here?

+3
source share
1 answer

The method includesdoes not do what you think. Replace joinswith includes, and it should do what you mean:

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

or perhaps:

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

joins JOIN SQL-, WHERE . include Active Record , . , Active Record ( ) "--", .

+2

All Articles