Reputation: 3870
I have a model named feedback
with attributes, rating and review. A product
may have a feedback, a appointment
may have a feedback, a user
may have a feedback.
I could add individual fields, like user_id, product_id, appointment_id in the feedbacks table, but that does not seem to be a very good scalable solution. The other option in my mind is to use a generalized, reference_id field, and a reference_model field which can be populated with the model name converted to string, and then I could manually interpret if the id entered in reference_id belongs to a user, product or an appointment.
What would be the best way of going about associating each feedback with any one of the 3 models, at a given time?
Upvotes: 1
Views: 57
Reputation: 4118
You should read about Polymorphic Associations.
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
There's even a nice RailsCast.
Upvotes: 5