John Fadria
John Fadria

Reputation: 1945

Each instance of the model has one or more instances of another model

How to indicate that each instance of the model has one or more instances of another model.

I always see how to indicate one-to-many (each instance of the model has zero or more instances of another model) with the has_many - belongs_to

Typically

class Order < ActiveRecord::Base
  has_many :line_items 

class LineItem < ActiveRecord::Base
  belongs_to :cart

But for a relationship Order ----> 1..n LineItem ????

Upvotes: 0

Views: 118

Answers (3)

b-m-f
b-m-f

Reputation: 1328

class Cart < ActiveRecord::Base

    has_many :line_items
    validates_presence_of :line_item_id
end

I think this is what you want. The cart should have 1...n Line Items.

Upvotes: 0

tagCincy
tagCincy

Reputation: 1599

On LineItem, add validates_presence_of :cart_id

On Cart, add inverse_of :cart to the has_many declaration

Official Rails solution: http://guides.rubyonrails.org/active_record_validations.html#presence

Upvotes: 1

Mohamad
Mohamad

Reputation: 35349

You would still use has_many and belongs_to. But you have to be sure that an instance of the parent can not exist without any instances of the child, and vice-versa. You can do this in several ways. From the child side:

  1. Create the parent object first. Only create child instances if there is a parent to assign to
  2. Create both objects at the same time using nested forms
  3. Use validations to ensure that the child has a parent before saving it

Or from the parent side:

  1. Create an Order only if there are LineItem to assign to it
  2. Create the Order but do not alter its state until you have added LineItems
  3. Create both at the same time using nested forms

There are a few more scenarios, but this illustrates the point. It really depends on how you model your objects.

Upvotes: 1

Related Questions