[英]Do not create polymorphic association if ID and Type the same?
I'm having trouble getting my validation to act correctly.我无法正确执行验证。
I keep getting the error because of my validate
method:由于我的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
Then I have a link you can click to subscribe to a product in the controller:然后我在controller有一个链接你可以点击订阅一个产品:
def subscribe_product
@product = Product.find(params[:id])
subscription = Subscription.new
subscription.subscriber = current_user
@product.subscriptions << subscription
@product.save
redirect_to :back
end
Why am I getting this error?为什么会出现此错误?
Add to subscription model:添加订阅model:
validates_uniqueness_of :subscribable_id, :scope => [:subscriber_id, subscribable_type]
And make sure you have has_many:subscriptions defined in product.rb并确保您在 product.rb 中定义了 has_many:subscriptions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.