1

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.

Relationships:

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

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) }    
end

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 }    
end

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.

engineersmnky
  • 25,495
  • 2
  • 36
  • 52
Bruno Farias
  • 785
  • 8
  • 22
  • ¿? what is your command in the console? I dont see quantity attribute in OrderItem model – DennisCastro Jun 21 '16 at 18:56
  • Dennis, the quantity was set in the migration, there is a column with this name in the order_items table. How should I set the order items? I have a doubt in this matter.. – Bruno Farias Jun 21 '16 at 18:59

1 Answers1

2

like this

order = Order.new(user: @user)
order.order_items << OrderItem.new(quantity: 100, item: Item.first)
DennisCastro
  • 161
  • 6