Zephyr4434
Zephyr4434

Reputation: 796

Rails - polymorphic associations with join models

I have been reading the Rails associations guides but I am still not sure if I am doing this correctly.

My app has Users and Products.

A User can contribute comments, reviews, and photos for those Products.

I figured that I would make a join model called Contributions:

  belongs_to :user
  belongs_to :building
  belongs_to :contributable, polymorphic: true

And then for User:

has_many :contributions, as: contributable
has_many :products, through: contributions

Products:

has_many :contributions, as: contributable
has_many :users, through: contributions

And then for example, in my Review model:

belongs_to :user
belongs_to :product

I don't feel like I am doing this right. Basically, I want a Contribution to always have an associated Product and User, but want contributions to be able to include either a Review, Comment, or Photo.

Is a join table with polymorphic associations the right way to go here?

Upvotes: 2

Views: 3327

Answers (1)

James
James

Reputation: 4737

I think something like this is what you're looking for.

class User < ActiveRecord::Base
  has_many :contributions
end

class Product < ActiveRecord::Base
  has_many :contributions
end

class Contribution < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
  belongs_to :contributable, :polymorphic => true
end

class Comment < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

class Review < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

class Photo < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

Make sure to have the contributable_id and contributable_type fields in your contributions table.

Upvotes: 4

Related Questions