Ruby on Rails Development ab initio (56)-ActiveRecord Foundation (One-to-many Association Relationship)

Source: Internet
Author: User
Tags ruby on rails

A One-to-many association allows us to represent a set of objects, for example, an order can contain any number of line item, and in the database, all line item records are associated with a foreign key to a particular order.

In an active record, belongs_to is used to specify the parent object in a child object by defining an association to a child object in the parent object's Has_many. We've learned about the belongs_to declaration in the last article, in fact, in one-to-many situations, and one-to-one, so let's understand the Has_many statement.

Has_many statement

Has_many declares a property that behaves like a set of child objects that can be treated as an array to access, query a particular object, or add a new object. For example:

Order = order.new
params[:p roducts_to_buy].each do |prd_id, qty|
Product = Product.find (prd_id)
order.line_items << lineitem.new (:p roduct => Product,
: Quantity => Qty) End

The Append operator (>>) does more than append an object to the Line_items list of the order, and sets the foreign key value of the Line_item object as the primary key value of the first, and saves it at the same time when the order object is saved Line_ The item object.

We can loop the Has_many association like an array:

order = Order.find (123) Total
= 0.0
Order.line_items.each do |li|
Total = li.quantity * Li.unit_price End

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.