1

I want to get the username of comment author like this

comment.commenter

models/comment.rb

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

models/user.rb

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

 validates :username, presence: true, uniqueness: true

 has_many :comments, as: :commenter
end

When i try to create Comment directly to db using this line of code:

Comment.create(commentable_type: 'Pokemon', commentable_id: 1, content: 'great', commenter: 1)

It throws this error

NameError: uninitialized constant Comment::Commenter
from /var/lib/gems/2.3.0/gems/activerecord-4.2.6/lib/active_record/inheritance.rb:158:in `compute_type'

I've read somewhere as: is used only for polymorphic assocciations so that might be the case of my error but couldn't figure out how to get around this problem

BozanicJosip
  • 506
  • 6
  • 22

2 Answers2

5

I don't think as: is what you are looking for. I think your issue is similar to the issue in belongs_to with :class_name option fails

Try

# user.rb
has_many :comments, foreign_key: "commenter_id"

# comment.rb
belongs_to :commenter, class_name: "User", foreign_key: "commenter_id"
Community
  • 1
  • 1
kcdragon
  • 1,724
  • 1
  • 14
  • 23
0

Let's explain a bit before going to the solution, if you write this code:

belongs_to :commentable, polymorphic: true

It implicitly means:

belongs_to :commentable, foreign_key: 'commentable_id', foreign_type: 'commentable_type', polymorphic: true

And

has_many :comments, as: :commentable

It specifies the syntax of polymorphic, that also means the foreign_key is commentable_id and foreign_type is commentable_type so if you want to change commentable to commenter, it is possible, you can do like this:

class Comment < ActiveRecord::Base
  belongs_to :commenter, foreign_key: 'commentable_id', foreign_type: 'commentable_type', polymorphic: true
end

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

That 's it!

For detail, please go through has_many and belongs_to documentation

Hieu Pham
  • 6,577
  • 2
  • 30
  • 50