LearningRoR
LearningRoR

Reputation: 27202

How to create a scope that compares association?

I have two models:

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

class Product
  belongs_to :user
  has_many :subscriptions, :as => :subscribable, :dependent => :destroy
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

In my product model, I'm trying to make a scope that compares the price or cost_per_unit of the Product to the Subscription. I just don't know how I would write this in SQL. So it should be something like:

class Product
  def self.lower_prices
   where( self.price < self.subscription.price OR self.cost_per_unit < self.subscription.cost_per_unit )
  end   
end

How would I write this?

Upvotes: 0

Views: 52

Answers (1)

jalvarado
jalvarado

Reputation: 196

You will need to specify a sql fragment in the where clause as well as use a join to get the data from the subscriptions table.

I don't have access to my development machine in order to test this but this should point you in the right direction hopefully.

class Product
  has_many :subscriptions, :as => :subscribable, :dependent => :destroy
  self.lower_prices
   Product.includes(:subscription).
   where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit" )
  end
end

Upvotes: 1

Related Questions