Rails predefines quite a few callback and filter - methods like before_create, anticipating that you may want to perform programming actions in your application but not dictating what those actions should be. These filters are analogous to the helper-file facility: They’re a halfway measure that makes it easy for you to add the finishing touches.
Rails预先定义了很多Method Hook,当你把这个hook放到一个model class里面的时候,Rails就会执行这个hook。至于执行什么事情,决定于你在这个Method Hook里面填写上了什么东西。比如:
It might be more graceful to have a default string value for the description field. If no description exists for the edition at the time the database record is first created, let’s have it default to “standard”.
To bring this about, insert the following method definition into edition.rb (just prior to the end that ends the file):
def before_create
self.description = "standard" unless description
end
This code basically says: if description is nil, set it to “standard”.
The code is executed just before a new edition is saved to the database. Thus any edition without a description gets one.
Sunday, March 11, 2007
Implementing predefined callback methods
Structured Freedom provided by Rails
You’re in charge of naming and writing the methods, but Rails provides an infrastructure that rationalizes and pre-systematizes the code for you.
An example of “structured freedom” are the method hooks available to you in your model definition files. A method hook is a method that you may, but aren’t obliged to, write; and if you do write it, it’s automatically called at a predefined point during program execution.
For example, if you write a method called before_create in one of your model files, then that method will be called automatically every time a database record corresponding to an instance of that model is created. This allows you to gatekeep the data in an orderly fashion and to manage your database at a low level while still writing everything in Ruby.