【问题标题】:Associating orders with products and customers in Rails在 Rails 中将订单与产品和客户相关联
【发布时间】:2014-03-11 13:22:11
【问题描述】:

我正在考虑一种模式,用户可以将产品添加到他的订单列表中,并且该订单将具有状态、评论等。多个用户可以有多个订单。每个订单都有一个产品。最好的方法是什么?

class User
  has_many :orders
end

class Order
  has_one :product
end

class Product
  belongs_to :category
  has_and_belongs_to_many :orders
end

或者我应该考虑使用 has_many :through 吗?另外,has_one 关联与 Product 模型具有的 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

虽然目前一切正常,但我很想听听任何 cmets 或建议

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 associations


    【解决方案1】:

    我认为最好的方法是:

    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
    

    有关协会的更多信息可以在这里找到:http://guides.rubyonrails.org/association_basics.html

    【讨论】:

    • 这是我的第一个猜测,起初似乎是正确的,但用户没有产品。并且产品不属于用户。
    • 用户可以拥有产品,而产品可以拥有使用我给出的答案的用户。 @user.products 将返回用户订购的所有产品,@product.users 将返回所有订购该产品的用户。 has_many :through 关联是它自己的关联类型。 guides.rubyonrails.org/…
    • 抱歉,这不是我想要的答案
    • 经过 2 天的研究,我现在不得不承认你是对的。这种类型的关联对我来说非常有用,但我想为可能有相同问题的人指出原因:当通过第三个中间模型关联时,很容易以两种方式访问​​对象,所以,例如,我可以轻松查看哪些用户对某些产品有待处理订单
    • 我很高兴能帮助丹尼斯!感谢您改变主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多