Ruby on rails 行为奇怪的轨道
我有rails版本Ruby on rails 行为奇怪的轨道,ruby-on-rails,activerecord,ruby-on-rails-3.2,associations,Ruby On Rails,Activerecord,Ruby On Rails 3.2,Associations,我有rails版本3.2.13和ruby版本1.9.3 我陷入了非常奇怪和有趣的境地 在我的应用程序中,有一个带有自定义验证器的“产品”模型 product.rb class Product < ActiveRecord::Base attr_accessible :description, :name, :price, :short_description, :user_id validates :name, :short_description, presence: true
3.2.13
和ruby版本1.9.3
我陷入了非常奇怪和有趣的境地
在我的应用程序中,有一个带有自定义验证器的“产品”模型
product.rb
class Product < ActiveRecord::Base
attr_accessible :description, :name, :price, :short_description, :user_id
validates :name, :short_description, presence: true
validates :price, :numericality => {:greater_than_or_equal_to => 0}
validate :uniq_name
belongs_to :user
belongs_to :original, foreign_key: :copied_from_id, class_name: 'Product'
has_many :clones, foreign_key: :copied_from_id, class_name: 'Product', dependent: :nullify
def clone?
self.original ? true : false
end
private
#Custom validator
def uniq_name
return if clone?
user_product = self.user.products.unlocked.where(:name => self.name).first
errors[:name] << "has already been taken" if user_product && !user_product.id.eql?(self.id)
end
end
当执行此行时调用自定义验证器@product=current_user.products.new(params[:product])
和自定义验证器的行#2
给我错误
undefined method `products' for nil:NilClass
我已在自定义验证器中检查了产品对象,但user\u id
为零。
为什么未自动分配用户id
谢谢你的帮助:)所以。。。绕过你的问题。为什么不验证名称的唯一性呢
验证:name,:除非=>:克隆的唯一性?
尝试将.new更改为.build
@product = current_user.products.build(params[:product])
并确保您的用户模型中有关系
Class User < ActiveRecord::Base
has_many :products
Class用户
尝试使用.build
而不是。new
您确定这是因为验证而不是因为当前用户为零而发生的吗?在您的验证代码中,一切正常。@gvalmon如果是nil user,则错误消息会有所不同-我想写,但是的,行未指定。您可以为错误添加行号和文件吗?@MichaelSzyndel他说“当执行这一行时,将调用自定义验证程序”。但验证器不应该在初始化时执行,这就是为什么我认为这个问题与当前用户有关。为什么你认为错误会有所不同?如果当前用户是nil,那么他试图调用nil上的“产品”。
Class User < ActiveRecord::Base
has_many :products