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