Reputation: 1945
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
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
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
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:
Or from the parent side:
There are a few more scenarios, but this illustrates the point. It really depends on how you model your objects.
Upvotes: 1