Why aren't my before_validation methods firing if some validation is scoped?
In my model I've got a couple of methods to populate attributes of an Invoice
before it is validated:
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.accou开发者_如何学运维nt.addresses.first
end
And in the controller:
@invoice = @account.invoices.build(:client_id => @client.id)
if @invoice.save
#it saved
end
My problem is that the associate_addresses
and generate_number
methods only fire if I remove the :scope => :client_id
argument on the :number
validation.
Why would it skip the before_validation
callbacks due to this?
Working in Rails 3.0.3
Thanks! Thanks.
Don't know why it's skipping the before_validation
methods, but to scope a uniqueness
validation in Rails 3 you should use the following syntax:
validates :number, :presence => true, :uniqueness => { :scope => :client_id }
I guess that your syntax is making it try to add a scope
validation, which doesn't exist. Probably there's a Rails bug that makes that skip the before_validation
methods.
精彩评论