Ruby on rails 在Rails中将订单与产品和客户关联
我正在考虑一个模式,用户可以将产品添加到他的订单列表中,并且该订单将具有状态、注释等。多个用户可以有多个订单。每个订单中有一个产品。最好的方式是什么Ruby on rails 在Rails中将订单与产品和客户关联,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,associations,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,Associations,我正在考虑一个模式,用户可以将产品添加到他的订单列表中,并且该订单将具有状态、注释等。多个用户可以有多个订单。每个订单中有一个产品。最好的方式是什么 class User has_many :orders end class Order has_one :product end class Product belongs_to :category has_and_belongs_to_many :orders end 我是否应该考虑与HasyMulk:通过?另外,产品模型与
class User
has_many :orders
end
class Order
has_one :product
end
class Product
belongs_to :category
has_and_belongs_to_many :orders
end
我是否应该考虑与HasyMulk:通过?另外,产品模型与habtm关联之间存在某种冲突,还是可以这样使用?谢谢
UPD1:经过一系列实验后,我做了以下几点:
class Order
belongs_to :user
belongs_to :product
end
class Product
belongs_to :category
has_many :orders
end
class User
has_many :orders
end
虽然目前一切都很顺利,但我很想听到任何评论或建议,我认为最好的办法是:
class User
has_many :orders
has_many :products, through: :orders
end
class Order
belongs_to :user
belongs_to :product
end
class Product
belongs_to :category
has_many :orders
has_many :users, through: :orders
end
更多关于关联的信息可以在这里找到:我认为最好的方法是:
class User
has_many :orders
has_many :products, through: :orders
end
class Order
belongs_to :user
belongs_to :product
end
class Product
belongs_to :category
has_many :orders
has_many :users, through: :orders
end
有关关联的更多信息可在此处找到:这是我的第一个猜测,起初似乎是正确的,但用户没有产品。产品不属于用户。用户可以拥有产品,产品可以让用户使用我给出的答案
@user.products
将返回用户订购的所有产品,@product.users
将返回订购该产品的所有用户。有很多:通过关联是它自己的关联类型。抱歉,但这不是我在寻找的答案。经过两天的研究,我现在不得不承认你是对的。这种类型的关联对我来说非常有效,但我想指出为什么对于可能有相同问题的人来说:当通过第三个中间模型关联时,很容易通过两种方式访问对象,因此,例如,我可以轻松检查哪些用户有特定产品的待定订单。我很高兴我可以帮助Denis!谢谢你改变主意。这是我的第一个猜测,一开始似乎是正确的,但用户没有产品。产品不属于用户。用户可以拥有产品,产品可以让用户使用我给出的答案@user.products
将返回用户订购的所有产品,@product.users
将返回订购该产品的所有用户。有很多:通过关联是它自己的关联类型。抱歉,但这不是我在寻找的答案。经过两天的研究,我现在不得不承认你是对的。这种类型的关联对我来说非常有效,但我想指出为什么对于可能有相同问题的人来说:当通过第三个中间模型关联时,很容易通过两种方式访问对象,因此,例如,我可以轻松检查哪些用户有特定产品的待定订单。我很高兴我可以帮助Denis!谢谢你改变主意。