简体   繁体   English

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

[英]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. 我知道有很多教程解释了如何在模型之间创建“ has_many through”关系,但是我认为我的问题既涉及技术方面,又涉及概念方面。

  • The objective is to create an online food ordering website 目的是创建一个在线食品订购网站
  • I created the Order, Item and OrderItem models. 我创建了Order,Item和OrderItem模型。

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. 谢谢你的时间。

like this 像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM