views:

99

answers:

4

Hi I am a complete newbie getting my feet with Rails, Please can someone help me in understanding the flow of the code

How CreditCardCallbacks, def before_validation(model) is invoked when we are not calling it directly.

class CreditCardCallbacks
# Normalize the credit card number
def before_validation(model)
model.cc_number.gsub!(/[-\s]/, '' )
end
end

class Order < ActiveRecord::Base
before_validation CreditCardCallbacks.new
# ...
end

class Subscription < ActiveRecord::Base
before_validation CreditCardCallbacks.new
# ...
end

Thanks in advance

A: 

This is where the dsl nature of rails comes in. Rails knows by the name of the method that it should be invoked before any validation code runs. In particular before Validations.validate is called

ennuikiller
Hi Thanks for your response.But can you please explain it in more detail
A: 

Model's valid? function will call *before_validation* before executing the actual validation.

JJ
+1  A: 

ActiveRecord exposes a number of "lifecycle" callbacks that allow you to hook into various portions of the validation and persistence process. See the Rails Guide to ActiveRecord Validations and Callbacks for more information.

(If you're interested in the source code that implements callbacks, you can take a look at it here, but it may be a little confusing if you've never done any metaprogramming in Ruby).

Greg Campbell
A: 

Pro Active Record: Databases with Ruby and Rails

by Kevin Marshall, Chad Pytel, Jon Yurek - 2007 - 304 pages

Get that book and read it. Thoroughly and clearly explains everything you want to know. A little old but still applies.

Mike Williamson