我有这个设置:
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
如何获取发表评论的用户名?
答案 0 :(得分:1)
您缺少评论所属者与用户关联:
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
这样你可以很容易地获取评论员:
@comment.user
答案 1 :(得分:0)
您可以使用委托
class Comment < ActiveRecord::Base
belongs_to :post
delegate :user, to :post
end
然后在您的代码中,您可以访问
@comment.user