Belongs_to alias

Jes*_*ist 1 ruby-on-rails ruby-on-rails-4

I want to get the username of comment author like this

comment.commenter
Run Code Online (Sandbox Code Playgroud)

models/comment.rb

class Comment < ActiveRecord::Base
 belongs_to :commenter
 belongs_to :commentable, polymorphic: true
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

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

kcd*_*gon 5

我不认为这as:是你要找的。我认为您的问题类似于belongs_to 中的问题,但 :class_name 选项失败

尝试

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

# comment.rb
belongs_to :commenter, class_name: "User", foreign_key: "commenter_id"
Run Code Online (Sandbox Code Playgroud)