In Ruby on Rails, a polymorphic association is a type of association that allows a model to belong to more than one other model on a single association. This is useful when you have a model that can be associated with multiple other models in a single association.
Here is an example of using a polymorphic association to define a relationship between a Comment
model and both a Post
and a Video
model:
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
class Video < ApplicationRecord
has_many :comments, as: :commentable
end
In this example, the Comment
model belongs_to
a commentable
model using a polymorphic association. This means that a Comment
can belong to either a Post
or a Video
model, depending on the value of the commentable_type
attribute. The Post
and Video
models both has_many
Comment
objects, specifying that they are the commentable
type for those Comment
objects.
Once the associations are defined, you can use them to access the associated objects in your code. For example, you can use the post.comments
method to access the Comment
objects associated with a Post
object:
post = Post.find(1)
post.comments # => Returns an array of `Comment` objects associated with the `Post`
You can also use the video.comments
method to access the Comment
objects associated with a Video
object:
video = Video.find(1)
video.comments # => Returns an array of `Comment` objects associated with the `Video`
Overall, polymorphic associations are a useful way to define relationships between models in Ruby on Rails when a model can belong to multiple other models on a single association. By using polymorphic associations, you can easily access and manipulate the associated objects in your code.
Top comments (0)