Ame*_*mey 2 ruby-on-rails associations models ruby-on-rails-4
我有三个型号
一个user谁提交productS和其他用户可以order该产品.
现在我想实现另一个模型payment,我作为管理员付钱给用户.
问题
我很困惑我应该在什么样的关联之间创建user,order和payment?
这就是我现在所拥有的:in app/models/user.rb
class User < ActiveRecord::Base
has_many :products_selling, class_name: 'Product'
has_many :orders_received, class_name: 'Order', through: :products_selling, source: :orders
has_many :orders_made, class_name: 'Order'
has_many :products_ordering, class_name: 'Product', through: :orders_made, source: :product
has_one :payment, class_name: 'Payment', through: :orders_received
Run Code Online (Sandbox Code Playgroud)
并在 app/models/order.rb
class Order < ActiveRecord::Base
belongs_to :product
belongs_to :buyer, class_name: 'User', foreign_key: :user_id
has_one :seller, class_name: 'User', through: :product
has_one :payment, through: :seller
Run Code Online (Sandbox Code Playgroud)
并在 app/models/payment.rb
class Payment < ActiveRecord::Base
belongs_to :user
belongs_to :order
Run Code Online (Sandbox Code Playgroud)
我不确定应该使用什么关联,我一直在阅读并且有一些使用的例子,polymorphic: :true但是他们都在使用has_many,在我的情况下,一个订单对应一个付款.
协会
多态关联基本上允许您使用单个表来管理多个关联:

因此,如果要将multiple表链接到single表,它实际上将创建一个pseudo对象,该对象可以与不同的数据类型相关联.我们通常使用多态关联与表可通过多种机型上使用,例如包括images,errors,posts等:

关于与has_many/的多态关联has_one,我不完全确定(如果你想,我可以研究)
-
固定
在你的情况下,我会这样做:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :orders
has_many :purchases, class_name: 'Order', foreign_key: "buyer_id"
has_many :products
has_many :bought, class_name: 'Product', through: :purchases
end
#app/models/order.rb
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :product
has_one :payment
end
#app/models/payment.rb
Class Payment < ActiveRecord::Base
#fields - id | user_id | order_id | created_at | updated_at
belongs_to :order #-> user pays for order
belongs_to :user #-> user making the payment
end
Run Code Online (Sandbox Code Playgroud)
这将允许您payments为每个创建order- 这实际上是付款,对吧?(你支付的order,而不是product)
| 归档时间: |
|
| 查看次数: |
3197 次 |
| 最近记录: |