Bruno Cabral Bruno Cabral - 9 months ago 38
Ruby Question

Rails relationship between three models confusing

I know there is a plenty of tutorials explaining how to create a 'has_many through' relationship between models, but I think my question is both technical and conceptual.

  • The objective is to create an online food ordering website

  • I created the Order, Item and OrderItem models.


class OrderItem < ActiveRecord::Base
belongs_to :item, conditions: "active = true"
belongs_to :order

class Order < ActiveRecord::Base
belongs_to :user
has_many :order_items
has_many :items, through: :order_items

validates :status, inclusion: { in: %w(ordered completed cancelled) }

class Item < ActiveRecord::Base
has_and_belongs_to_many :categories, join_table: :items_categories

has_many :order_items
has_many :orders, through: :order_items

validates_presence_of :title, :description
validates :price, numericality: { :greater_than=>0 }

Am I doing something wrong? Each order should be able to contain many items and the quantity of them.
I'm not very positive I'm doing the correct architecture for these models, as I can't assign the quantity via << operator, only assign the item.

Thanks for your time.


like this

order = @user)
order.order_items << 100, item: Item.first)