私はこのスコープまたは方法をどうすべきか混乱しています。私は、次の団体があります低価格を表示する方法または範囲を作成しますか?
モデル
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
と比較しながら、それが低いかどうかを確認します。
私はこの権利を行っていますか?何が修正される必要がありますか?
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>
私はこれについてどうやって行くのか混乱しています。私は 'UserProduct'(または' Price')属性を複製しなければならなかったので、より安い価格をチェックする方法を知っていました。 'サブスクリプション'と '価格'は同じフィールドを持っているので、私はこれら2つのモデルを比較することができると思う。したがって、「サブスクリプション」はすべての「価格」と比較されます。 – LearningRoR
また、あなたは自分のウェブサイトについて正しいです。ユーザーは新しい価格を入力する必要があります。代わりに、モデルを「価格」に変更したので、現在と将来の間に作成されます。ありがとうございました。 – LearningRoR
はい。最初は、サブスクリプションエンティティに価格フィールドがあることに気付かなかった。私はあなたのUIのどこかで、あなたはサブスクリプションを取得すると仮定したいと思います。私の他のアプローチは、価格モデルに安価な価格を返す方法を持たせることでした。基本的には、この回答で指定されたスコープでは、製品IDと価格を提供できるすべてのオブジェクトがスコープを使用できます。 –