三种模型之间的Rails关系令人困惑

时间:2016-06-21 17:56:49

标签: ruby-on-rails ruby activerecord rails-models

我知道有很多教程解释如何在模型之间建立'has_many through'关系,但我认为我的问题既是技术性的,也是概念性的。

  • 目标是创建一个在线食品订购网站
  • 我创建了Order,Item和OrderItem模型。

关系:

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

我做错了吗?每个订单应该能够包含许多项目及其数量。 我不是很肯定我正在为这些模型做正确的架构,因为我不能通过&lt;&lt;来分配数量。运算符,仅分配项目。

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

像这样

order = Order.new(user: @user)
order.order_items << OrderItem.new(quantity: 100, item: Item.first)
相关问题