Rails 三个模型之间的关系令人困惑
Rails relationship between three models confusing
我知道有很多教程解释如何在模型之间创建 'has_many through' 关系,但我认为我的问题既是技术问题也是概念问题。
- objective是创建一个在线订餐网站
- 我创建了 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
我是不是做错了什么?每个订单应该能够包含许多项目和它们的数量。
我不是很肯定我正在为这些模型做正确的架构,因为我无法通过 << 运算符分配数量,只能分配项目。
感谢您的宝贵时间。
像这样
order = Order.new(user: @user)
order.order_items << OrderItem.new(quantity: 100, item: Item.first)
我知道有很多教程解释如何在模型之间创建 'has_many through' 关系,但我认为我的问题既是技术问题也是概念问题。
- objective是创建一个在线订餐网站
- 我创建了 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
我是不是做错了什么?每个订单应该能够包含许多项目和它们的数量。 我不是很肯定我正在为这些模型做正确的架构,因为我无法通过 << 运算符分配数量,只能分配项目。
感谢您的宝贵时间。
像这样
order = Order.new(user: @user)
order.order_items << OrderItem.new(quantity: 100, item: Item.first)