1

I have the Comment model which belongs to some other models like Post, Page etc and has_one (or belongs_to?) User model. But I need the User to be commentable too, so User has to have many Comments from other Users (this is polymorphic :commentable association) and he has to have his own Comments, written by him. What is the best way to make an association like this? How can I read and create Comments for User in a controller if User has two different associations with Comments? Now I do this and it's not right I guess:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :comments, as: :commentable
  has_many :comments
end

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

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :content
      t.references :commentable, polymorphic: true, index: true
      t.belongs_to :user
      t.timestamps null: false
    end
  end
end

1 Answer 1

3

You'll want to use another name for that association.

has_many :comments, as: :commentable
has_many :commented_on, class_name: 'Comment' # you might also need foreign_key: 'from_user_id'.

See has_many's documentation online.

The foreign_key should not be needed in your case, but I'm pointing it out Just In Case™. Rails will guess "{class_lowercase}_id" by default (so user_id in a class named User).

Then you can access both associations (The class_name is explicitly needed because Rails can't find Comment from commented_on).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.