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.