我很困惑我应该如何制定这个范围或方法。我有以下的关联:创建方法或范围以显示较低的价格?
模型
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
较低的价格属于与Subscription
相同Product
,同时将其自身与订阅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>
我也很困惑如何去做这件事。我必须复制'UserProduct'(或'Price')属性,以便知道如何检查便宜的价格。由于'Subscription'和'Price'具有相同的字段,我想我可以比较这两个模型。所以'订阅'将与所有的“价格”进行比较。 – LearningRoR 2012-04-12 14:58:42
另外,你对我的网站是正确的。用户必须输入新的价格。我改变了模型为'价格',所以它从现在开始,并在未来。谢谢。 – LearningRoR 2012-04-12 15:00:20
是的。起初我没有注意到认购实体有价格字段。我假设你的用户界面的某个地方,你会得到订阅。我的另一种方法是让价格模型有办法返回更便宜的价格。基本上,通过本答案中给出的范围,任何可以提供产品ID和价格的对象都可以使用范围。 – 2012-04-12 17:40:48