如果ID和Type相同,请不要创建多态关联?

时间:2012-04-07 19:57:20

标签: ruby-on-rails ruby-on-rails-3

我无法让我的验证行事正确。

由于我的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

为什么我收到此错误?

1 个答案:

答案 0 :(得分:3)

添加到订阅模式:

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

并确保您在product.rb中定义了has_many:subscriptions