2011-02-14 36 views
1

在我的模型我有兩個方法來填充Invoice的屬性,它被確認之前:爲什麼我的before_validation方法不會觸發如果某些驗證範圍?

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 

和Controller:

@invoice = @account.invoices.build(:client_id => @client.id) 

if @invoice.save 
    #it saved 
end 

我的問題是,associate_addressesgenerate_number只有在刪除:number驗證中的:scope => :client_id參數時才觸發。

爲什麼會因此跳過before_validation回調?

Working in Rails 3.0.3

謝謝! 謝謝。

回答

2

不知道爲什麼它跳過before_validation方法,但範圍在Rails 3的一個uniqueness驗證你應該使用下面的語法:

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

我猜你的語法,使得它嘗試添加scope驗證,它不存在。可能有一個Rails的錯誤,使得跳過before_validation方法。

+1

我似乎有一個類似的問題。驗證看起來有效,但完全無效的數據通過,並且.valid?始終返回true。你有什麼想法從哪裏開始尋找導致這種情況發生的原因? – Avishai

相關問題