【问题标题】:Why aren't my before_validation methods firing if some validation is scoped?如果某些验证是作用域的,为什么我的 before_validation 方法不会触发?
【发布时间】:2011-06-26 16:04:13
【问题描述】:

在我的模型中,我有几种方法可以在验证 Invoice 之前填充其属性:

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

我的问题是 associate_addressesgenerate_number 方法只有在我删除 :number 验证中的 :scope => :client_id 参数时才会触发。

为什么它会因此跳过before_validation 回调?

在 Rails 3.0.3 中工作

谢谢! 谢谢。

【问题讨论】:

    标签: ruby-on-rails validation callback


    【解决方案1】:

    不知道为什么它会跳过 before_validation 方法,但要在 Rails 3 中限定 uniqueness 验证,您应该使用以下语法:

    validates :number, :presence => true, :uniqueness => { :scope => :client_id }
    

    我猜你的语法让它尝试添加一个不存在的scope 验证。可能有一个 Rails 错误导致跳过 before_validation 方法。

    【讨论】:

    • 我似乎遇到了类似的问题。验证显示有效但完全无效的数据通过,并且 .valid?总是返回真。您知道从哪里开始寻找导致这种情况发生的原因吗?
    猜你喜欢
    • 2011-02-18
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多