fibono
fibono

Reputation: 783

How to access "belongs_to" object in polymorphic associations?

I'm having difficulty accessing a model in a "belongs_to" association. I have "post" and "comment" models that each can have many "likes." Right now, I can access

comment.likes

or

post.likes

but I get an "undefined method" if I try

like.comment

I attempted to implement the Rails associations as follows:

class Post < ActiveRecord::Base
  include Likeable

....

class Comment < ActiveRecord::Base
  include Likeable

I have a "Likeable" module:

module Likeable
  extend ActiveSupport::Concern

  included do
    has_many :likes, as: :likeable,
      class_name: "Like",
      dependent: :destroy
  end

My "Like" model looks partly as follows:

class Like < ActiveRecord::Base
  validates :author_id, presence: true, uniqueness: { scope: [:likeable_id, :likeable_type]}

  belongs_to :likeable, polymorphic: true

I believe everything is setup correctly on the database layer. How does the above Rails layer look? Any suggestions/advice appreciated! Thanks!

Upvotes: 1

Views: 1514

Answers (1)

smathy
smathy

Reputation: 27971

The whole idea of a polymorphic association is that from the Like side of things, you don't need to know what it's associated to in order to call that associated object.

Ie. you should access the associated object with just like.likeable and that will return either a Comment or a Post instance, depending on which one this Like is associated with.

Upvotes: 3

Related Questions