Ruby on rails 为什么不';如果某个验证的作用域已确定,是否会触发my before_验证方法?
在我的模型中,我有两种方法在验证前填充Ruby on rails 为什么不';如果某个验证的作用域已确定,是否会触发my before_验证方法?,ruby-on-rails,validation,callback,Ruby On Rails,Validation,Callback,在我的模型中,我有两种方法在验证前填充发票的属性: validates :account_id, :presence => true validates :account_address, :presence => true validates :number, :presence => true validates :number, :uniqueness => true, :scope => :client_id before_validation :gene
发票的属性:
validates :account_id, :presence => true
validates :account_address, :presence => true
validates :number, :presence => true
validates :number, :uniqueness => true, :scope => :client_id
before_validation :generate_number, :associate_addresses, :on => :create
def generate_number
self.number = self.client.invoices.count + 1
end
def associate_addresses
self.account_address = self.account.addresses.first
end
在控制器中:
@invoice = @account.invoices.build(:client_id => @client.id)
if @invoice.save
#it saved
end
我的问题是,只有在我删除:number
验证上的:scope=>:client\u id
参数时,关联\u addresses
和生成\u number
方法才会触发
为什么它会因此跳过\u验证之前的
回调
在Rails 3.0.3中工作
谢谢!
谢谢。我不知道为什么在验证之前跳过
方法,但是要在Rails 3中定义唯一性
验证,应该使用以下语法:
validates :number, :presence => true, :uniqueness => { :scope => :client_id }
我猜您的语法让它尝试添加一个范围
验证,但它并不存在。可能是Rails的一个bug使得它跳过了验证之前的方法。我似乎也遇到了类似的问题。验证看起来有效,但数据传递完全无效。有效吗?总是返回true。你知道从哪里开始寻找导致这种情况发生的原因吗?