Ruby on Rails development from scratch (41)-ActiveRecord Foundation (storage of structured data)

Source: Internet
Author: User
Tags serialization ruby on rails

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.