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
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
).