Sometimes it is convenient to be able to store any Ruby object directly in an attribute, in the same way that an active record supports serialization, transforms a Ruby object into a ymal string, and stores the string in the database field corresponding to the attribute. In a database definition, this field must be of type text.
Because the active record maps the char and text types in the database to the string type of ruby, if we need to tell the active record to use serialization, for example, we want to know the last 5 consumption of a customer We create a table containing the text Type field to hold the information:
CREATE TABLE purchases (
ID int not NULL auto_increment,
name varchar (MB) NOT NULL,
last_five text,
Prim ary Key (ID)
);
In the active record class that converts this table, we use the Serialize () declaration to tell the active record to arrange the objects:
Class Purchase < activerecord::base
serialize:last_five
#
... End
When we create a new purchase object, we can assign any value to the Last_five column, in which case we set up a string array for the Last_five column,
Purchase = purchase.new
purchase.name = "Dave Thomas"
purchase.last_five = [' Shoes ', ' shirt ', ' socks ', ' ski mas K ', ' shorts ']
purchase.save
When we read it, this property has been set to an array:
Purchase = Purchase.find_by_name ("Dave Thomas")
pp purchase.last_five
pp purchase.last_five[3]
The output of the code is:
["Shoes", "shirt", "socks", "ski Mask", "shorts"]
" Ski Mask "
Although this feature is powerful and convenient, it is only if you do not intend to use the serialized information in projects other than Ruby unless the program can use the Ymal format. In particular, this information is difficult to use by SQL queries, and you might consider using aggregation (aggregation) instead, which we'll introduce later to achieve the same effect.