Ruby on Rails development from scratch (54)-ActiveRecord Foundation (Specify association Relationship)

Source: Internet
Author: User
Tags ruby on rails

Rails supports three of relationships between tables, one-to-one, One-to-many, Many-to-many, and you need to include a declaration in model to identify these associations: Has_one,has_many,belongs_to,has_and_belongs_to_many.

A one-to-one association may exist in a relationship such as an order and an invoice, and an order can have only one invoice, which we specify in rails:

Class Order < ActiveRecord::Base
Has_one:invoice ...
Class Invoice < activerecord::base
Belongs_to:order
...

The relationship between the order and the entry is One-to-many, and we declare this:

Class Order < ActiveRecord::Base
Has_many:line_items ...
Class LineItem < activerecord::base
Belongs_to:order
...

We may classify goods, a product may fall into several categories of goods, and a category of goods may have a variety of goods, goods and classifications of the relationship between the many to many, in rails, we declare:

Class Product < activerecord::base
has_and_belongs_to_many:categories
...
Class Category < activerecord::base
has_and_belongs_to_many:p roducts
...

The above definitions of associated relationships add methods to model to navigate through the associated objects, followed by a discussion of the three related relationships.

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.