Tony Beninate
Tony Beninate

Reputation: 1985

Rails polymorphic comments associate

Trying to work out an polymorphic association where Comments can belong to, for example, Photos and Users. Where a Comment on a user is treated as a "direct message". But I'm getting the User association a bit messed up.

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class Photo < ActiveRecord::Base
  has_many :comments, as: :commentable, dependent: :destroy
end

class User < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :messages, as: :commentable
end

This is incorrect. Ideally, user.comments should retrieve all Comment records where user_id == user.id and something like user.messages should retrieve all Comments where the type is User and they are the subject.

Upvotes: 0

Views: 263

Answers (2)

Bogdan
Bogdan

Reputation: 209

Relationships:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  belongs_to :user
end

class Photo < ActiveRecord::Base
  has_many :comments, as: :commentable, dependent: :destroy
end

class User < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :messages, as: :commentable, class_name: 'Comment'
end

Schema:

# Comments
 ...
 t.integer :user_id
 t.integer :commentable_id
 t.string :commentable_type
 ...

Then you can invoke:

@user.comments # Get all comments created by particular user
@user.messages # Get all comments where particular user is a subject

Upvotes: 1

Caleb Keene
Caleb Keene

Reputation: 388

have you added the foreign key and type columns to the comments table? within a migration file:

  def change
    add_column :comments, :commentable_type, :integer
    add_column, :commentable_type, :string
    add_index :comments, [:commentable_type, :commentable_id]
  end

Also make sure you have a Message model and it has the associations

class Message < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  belongs_to :commentable, polymorphic: true
end

Upvotes: 0

Related Questions