2012-04-07 40 views
1

我無法讓我的驗證正確執行。如果ID和Type相同,不要創建多態關聯?

我不斷收到,因爲我validate方法的錯誤:

NoMethodError in ProductsController#subscribe_product 

undefined method `subscriptions' for #<Class:0x6da5890> 

class Subscription < ActiveRecord::Base 
    belongs_to :subscriber, :class_name => "User" 
    belongs_to :subscribable, :polymorphic => true 

    validates :subscriber_id, :presence => true 
    validates :subscribable_id, :presence => true 
    validates :subscribable_type, :presence => true 

    validate do |s| 
    if s.subscribable_type.constantize.subscriptions.find_by_subscribable_id_and_subscribable_type(s.subscribable_id, s.subscribable_type) 
     s.errors.add_to_base "You're already susbcribed to this Product." 
    end 
    end 
end 

然後,我有一個鏈接,您可以點擊訂閱控制器產品:

def subscribe_product 
@product = Product.find(params[:id]) 
subscription = Subscription.new 
subscription.subscriber = current_user 
@product.subscriptions << subscription 
@product.save 
redirect_to :back 
end 

我爲什麼開始g這個錯誤?

回答

3

添加到訂閱模式:

validates_uniqueness_of :subscribable_id, :scope => [:subscriber_id, subscribable_type] 

並確保您擁有的has_many:在product.rb

定義訂閱