In Rails, how are validators, for example "validates_numericality_of" implemented?
I'm new to the Ruby language and the Rails framework. When I saw this piece of codes from the "Head First Rails" book:
class ClientWorkout < ActiveRecord::Base
validates_numericality_of :paid_amount
end
My questions are:
开发者_StackOverflow社区1) From the Ruby language, where and how is validates_numericality_of implemented? Is it available to Ruby classes outside the ActiveRecord framework
2) What does validates_numericality_of do to the instances of the ClientWorkout class?
Thanks.
1) validates_numericality_of is one of many validations that exists in the Rails framework, or ActiveRecord to be more precise. So it is not something that is accesible for all Ruby classes. You use it be passing ruby symbols that represents attributes for the model. You can pass several attributes at the same time:
validates_numericality_of :age, :score
But you can also specify the validation several times if you want different settings for different attributes:
validates_numericality_of :age
validates_numericality_of :score, :allow_nil => true
2) What validations in general do is to validate if the model is "valid" before saving to database when ClientWorkout.save() is called. validates_numericality_of does as the name implies validate that the passed attribute(s) are numeric and not a string, array, boolean etc.
If any of the validations is not fulfilled then the record will not be saved to database. This can of course be bypassed by calling ClientWorkout.save(false) which will tell ActiveRecord to save without validating the record.
validates_numericality_of validates whether the value of the specified attribute is numeric.
Active Record is your Model and each model corresponds to a table in the database. So if you use validates_numericality_of in the ClientWorkout Class that would validate only the paid_amount in that class/model.
精彩评论