Belongs_to别名

时间:2016-08-21 03:48:20

标签: ruby-on-rails ruby-on-rails-4

我想获得评论作者的用户名

comment.commenter

模型/ comment.rb

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

模型/ 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

当我尝试使用以下代码行直接向db创建Comment时:

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

它会抛出此错误

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'

我在某处读过:仅用于多态关联,因此可能是我的错误,但无法弄清楚如何解决这个问题

2 个答案:

答案 0 :(得分:3)

我认为as:不是你想要的。我认为您的问题类似于belongs_to with :class_name option fails

中的问题

尝试

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

# comment.rb
belongs_to :commenter, class_name: "User", foreign_key: "commenter_id"

答案 1 :(得分:0)

如果您编写此代码,请在解决之前解释一下:

belongs_to :commentable, polymorphic: true

隐含地意味着:

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

has_many :comments, as: :commentable

它指定了多态的语法,这也意味着foreign_keycommentable_idforeign_typecommentable_type所以如果你想将commentable更改为评论者,有可能,你可以这样做:

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

就是这样!

有关详情,请浏览has_manybelongs_to文档