ruby-on-rails - 将订单与 Rails 中的产品和客户关联

标签 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

或者我应该考虑使用 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

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

最佳答案

我认为最好的方法是:

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

关于ruby-on-rails - 将订单与 Rails 中的产品和客户关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22326983/

相关文章:

ruby-on-rails - Rails Runner 抛出 : undefined local variable or method `app' for main:Object (NameError)

ruby-on-rails - 使用 rails f.select helper 预选一个选项?

javascript - 如何格式化 Ruby 数组以用作 Highcharts 中的数据

ruby-on-rails - 如何记录某个 url 的整个请求( header 、正文等)?

javascript - 如何在rails应用程序中包含angularjs库文件

javascript - rails | Javascript同步多个字段,避免无限循环

mysql - Rails 有很多 :through relationship causing stack level too deep

ruby-on-rails - 在每个循环 rails 中获取数据

ruby-on-rails - Accepts_nested_attributes_for Rails 3 中的实际形式使用

javascript - 禁用 JavaScript 的 RoR