Amey
Amey

Reputation: 8548

A model that belongs_to two models or a polymorphic association?

I have three models

  1. User
  2. Product
  3. Order

A user who submits products and other users can order that product.

Now I want to implement another model payment, where I as an admin pay the user.

Question I am confused about what kind of association should i create between user, order and payment?

This is what I currently have : 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

and in 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

and in app/models/payment.rb

class Payment < ActiveRecord::Base
  belongs_to :user
  belongs_to :order

I am not sure what association should be used, I have been reading and there are examples using polymorphic: :true but they were all with has_many, where as in my case one order corresponds to one payment.

Upvotes: 4

Views: 4880

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

Associations

Polymorphic associations basically allow you to use a single table to manage multiple associations:

enter image description here

So if you wanted to link multiple tables to a single table, it will essentially create a pseudo object, which can be associated with different data types. We typically use polymorphic associations with tables which can be used by multiple models, examples including images, errors, posts etc:

enter image description here

In regards to relating polymorphic associations to has_many / has_one, I'm not entirely sure (I can research if you want)

--

Fix

In your case, I would do this:

#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

This will allow you to create payments for each order - which is really what payments are for, right? (You pay for the order, not the product)

Upvotes: 6

Related Questions