I’m confused on how I should make this scope or method. I have the following associations:
Models
class User
has_many :prices
has_many :products, :through => :prices
has_many :subscriptions, :foreign_key => :subscriber_id
end
class Product
has_many :prices
has_many :users, :through => :prices
end
class Price
# Table columns => :product_id, :cost, :user_id
belongs_to :user
belongs_to :product
belongs_to :store
has_many :subscriptions, :as => :subscribable
end
class Subscription
# Table columns => :product_id, :cost, :subscriber_id, :subscribable_id
# :subscribable_type
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
validates_uniqueness_of :subscribable_id, :scope =>
[ :subscriber_id, :subscribable_type]
end
So the method should be something like:
class Price
def self.lower_price
if self.product_id == self.subscription.product_id
if self.cost < self.subscription.cost
end
end
end
end
What this method is suppose to do is show only lower prices of UserProducts that belong to the same Product as the Subscription, while comparing itself to the subscriptions price field to see if its lower.
Am I doing this right? What needs to be fixed?
EDIT
class Price < ActiveRecord::Base
scope :for_product, lambda { |product_id| where( :product_id => product_id) }
scope :cheaper, lambda { |cost| where(["prices.cost < :cost", { :cost => cost } ] ) }
end
class Subscription < ActiveRecord::Base
def cheaper_prices
Price.for_product(product_id).cheaper(cost)
end
end
PrivatePagesController:
def watch
@prices = Price.cheaper_prices.paginate(:page => params[:page], :per_page => 20).order('purchase_date DESC')
end
This gives me the error:
NoMethodError in PrivatePagesController#watch
undefined method `cheaper_prices' for #<Class:0x6f99210>
I figured that you are making a web site where users enter prices they found and subscribe to find cheaper prices. I’d rename the UserProduct entity to Price.
It’s ambiguous whether subscribers subscribe to a product or to a price. If you clear that up, it may simplify away the polymorphic association. Let’s say that they subscribe to a product with a given price. Then you want the following: