我对如何制作这个范围或方法感到困惑。我有以下关联:
楷模
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
所以方法应该是这样的:
class Price
def self.lower_price
if self.product_id == self.subscription.product_id
if self.cost < self.subscription.cost
end
end
end
end
该方法的目的是仅显示UserProducts
与 相同Product
的价格较低的价格Subscription
,同时将自身与订阅price
字段进行比较以查看其是否较低。
我这样做对吗?需要修复什么?
编辑
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>