Ruby on Rails Development ab initio (55)-ActiveRecord Foundation (one-to-one association relationship)

Source: Internet
Author: User
Tags ruby on rails

A one-to-one association, or, more correctly, a pair of 0 or one-to-one associations, is implemented by a foreign key reference to at most one record in another table, and the following figure describes the relationship between the Orders table and the Invoices table:

In an active record, to represent such a relationship requires adding a Has_one:invoice declaration to the Order class and adding a declaration Belongs_to:order in the invoice class, in fact, we can think of this association as Mutual, We can make invoice have an order, or we can have a invoice for the order, but when we store the object in the database, if we give an object a Has_one association to another existing object, the associated object will be saved automatically. For example:

An_invoice = Invoice.new (...)
Order.invoice = an_invoice # Invoice gets saved

If we give an object a belongs_to association to another object, it will not be saved automatically, for example:

Order = order.new (...)
An_invoice.order = Order # Saved

There is another difference, when you give an object a Has_one association, if you point to a surviving child object, the Foreign key Association of the existing object will be removed, that is, clear zero, the following figure:

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.