0

我有这个设置:

class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy  
  has_many :comments, :through => :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

如何获取发表评论的用户名?

4

2 回答 2

1

您缺少 Comment-belongs-to-User 关联:

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

这样你就可以很容易地获取评论者:

@comment.user
于 2013-05-26T12:47:58.923 回答
0

您可以使用委托

class Comment < ActiveRecord::Base
  belongs_to :post

  delegate :user, to :post
end

然后在您的代码中您可以访问

@comment.user
于 2013-05-26T16:13:27.860 回答