Monday, February 11, 2013

Experimenting autosave

(This experiment is performed using Ruby version 1.9.3 and Rails version 3.0.9)

When we define a one-to-one or one-to-many relationship in Rails, very likely we're gonna want the child object(s) to be saved to database when parent object is saved. For example, we have an Order class, which has a one-to-many relationship to an OrderLineItem class. After we initialize an order object and associate it with several order line item objects, we're gonna want to save the order object. Whether the related line item objects will be saved depends on how you specify the autosave option of the has_many relationship (it also exists in has_one and belongs_to relationships). Below is how Ruby on Rails documentation say about autosave.

:autosave
If true, always save the associated objects or destroy them if marked for destruction, when saving the parent object. If false, never save or destroy the associated objects. By default, only save associated objects that are new records.

Clear enough, right? If :autosave is defined to be false, no change will be applied to the child database when the parent object is saved, even though there are a bunch of child objects associated to the parent object. If defined to be true, all the changes will be applied to the child database when the parent object is saved, no matter these child objects are new or initialized from existing records in database. Finally if by default, only those new child objects will be saved to database when parent object is saved.

You can experiment it by using the following example code. Assume we have a order record in orders table and a order line item record in order_line_items table associated to that order record, and assume quantity, one of the attributes, of that order line item is 10.

Let's type in the following commands in console when autosave is set to be true and default respectively.

o = Order.first 
order.line_items.first.quantity = 5
o.save!


If autosave is set to true. Go to the database after these commands, you will find the quantity is updated to 5.
If autosave is set to default. Go to the database after these commands, you will find the quantity is still 10.


Let's type in a different set of commands in console when autosave is set to be default and false respectively.

o = Order.first
order.line_items << new_line_item # assume we have created a new line item object called new_line_item
o.save!


If autosave is set to default. Go to the database after these commands, you will find the new_line_item is saved to db.
If autosave is set to false. Go to the database after these commands, you will find the new_line_item is NOT saved to db.

No comments:

Post a Comment