Rails Development Details (vii) ACTIVERECORD Associations Association

Source: Internet
Author: User

1. Why do I need to associate

Many times, such as E-commerce users and orders, a user will have a lot of orders, an order belongs to only one user, this is an association.

When creating an order, you need to use the householder key as a foreign key to delete the user's order while deleting the user's.

In rails, you can associate an order like this to the following.

Class Customer < ActiveRecord::Base 
  has_many:orders,:d ependent =>:d estroy 
End 
      
Class Order < ActiveRecord::Base 
  belongs_to:customer 
End

You can create orders like the following, deleting users.

@order = @customer. Orders.create (: order_date => time.now) 
     
@customer. Destroy

2. Type of association

is associated with the following 6.

Belongs_to

Has_one

Has_many

Has_many:through

Has_one:through

Has_and_belongs_to_many

2.1.belongs_to

BELONGS_TO is a one-to-one association. Express a kind of relationship that belongs to.

Just like an order can only belong to a user. There is a field in the order table that stores the user's primary key, which is the foreign key of the order table.

Class Order < ActiveRecord::Base 
  Belongs_to:customer 
End

2.2.has_one

Has_one is also a one-to-one association. Expressing a relationship that has one.

Just like a supplier can only have one account. The Account table has a supplier primary key, which is the foreign key of the account table.

Class Supplier < activerecord::base 
  Has_one:account 
End

2.3.has_many

Has_many is a one-to-many association. Expresses a number of relationships.

Just like a user has multiple orders.

Class Customer < activerecord::base 
  has_many:orders 
End

The name associated with Has_many needs to be in the plural form.

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.