Tuesday, January 15, 2008

The 'new' Method of ActiveRecord Further Explained

As I continue my study of RubyOnRails using Build Your Own Ruby On Rails Web Applications, I'm including expansions on certain topics that piqued my interest. First, here are a few useful links if you're reading the book too.

As I continued my study of RubyOnRails, I noticed that the new method was being called with a params hash on page 157. The params hash picks up the user data on the example submission form. The hash is passed to the 'new' method and a new object is magically created with its fields automatically assigned the values that the user submitted on the web form.

Previously in the book, I had seen 'new' called with no arguments, but I hadn't seen this hash argument version of the method. A little research into the Rails Framework documentation for 'new' shed some light on the situation.

It turns out that 'new' can be called in four different ways. The first way is the no argument version I mentioned above. A new object is created with empty attributes. The second usage of new is to pass the attribute values in an argument list like:

new_gadget = Gadget.new(:attr_1=> 25, :attr_2=> 32)

This usage will create a new object with its attributes set to the specified values.

The 'new' method can also be called using block initialization:

new_gadget = Gadget.new do |g|
g.attr_1 = 25
g.attr_2= 32

And finally, as shown in the example on page 157, the 'new' method can be called with a hash:

new_gadget = Gadget.new(params[:gadget])

In this case, the hash contains attribute/value pairs that are named with the symbols :attr_1 and :attr_2.

No comments: