Oskar
Oskar

Reputation: 13

Associate Rails active model with two different models

Is there a way to use inheritance with Ruby on Rails Active Model?

I have two models to which I want to add comments. It would be cool if I can just use one Comment model that could be associated with both models.

Upvotes: 0

Views: 85

Answers (1)

Simple Lime
Simple Lime

Reputation: 11035

Look into Polymorphic Associations

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Article < ApplicationRecord
  has_many :comments, as: :commentable
end

class Image < ApplicationRecord
  has_many :comments, as: :commentable
end

Upvotes: 2

Related Questions