此处的示例行无效。我尝试了20种。
视图/评论/ _comments.html.erb
<% @comments.each do |comment| %>
<%= User.find(comment.user_id).name %> # Gives user name of commenter
<%= simple_format comment.content %>
<%= pluralize(comment.likes, 'like') %>
<%= link_to content_tag(:span, '', class: 'glyphicon glyphicon-thumbs-up') +
' Like it', like_comment_path(:id => comment.id), method: :post %>
<%= User.find(like.user_id).name %> # How to get user name of liker?
<% end %>
comments_controller.rb
def like
@comment = Comment.find(params[:id])
comment_like = current_user.comment_likes.build(comment: @comment)
if comment_like.save
@comment.increment!(:likes)
@comment.create_activity :like
@user = User.find(params[:id])
flash[:success] = 'Thanks for liking!'
else
flash[:error] = 'Two many likes'
end
redirect_to(:back)
end
comment_like.rb
class CommentLike < ActiveRecord::Base
belongs_to :comment
belongs_to :user
validates :user, uniqueness: { scope: :comment }
end
comment.rb
class Comment < ActiveRecord::Base
include PublicActivity::Common
# tracked except: :update, owner: ->(controller, model) { controller && controller.current_user }
has_many :comment_likes
has_many :likers, through: :comment_likes, class_name: 'User'
belongs_to :commentable, polymorphic: true
belongs_to :user
end
答案 0 :(得分:1)
评论有很多喜欢。所以你正在寻找评论员。
class Comment
has_many :comment_likes
has_many :likers, through: :comment_likes, class_name: 'User', source: :liker
end
class CommentLikers
belongs_to :liker, class_name: 'User', foreign_key: :user_id
belongs_to :liked_comment, class_name: 'Comment', foreign_key: :comment_id
end
class User
has_many :comment_likes
has_many :liked_comments, through: :comment_likes, class_name: 'Comment', source: :liked_comment
end
然后在你的观点中:
<% @comments.each do |comment| %>
<% comment.likers.each do |user| %>
<%= user.name %>
<% end %>
<% end %>
编辑1
您的问题在导轨指南中得到了很好的解释: http://guides.rubyonrails.org/association_basics.html
但只是给你一个简短的解释:
您需要通过评论将评论与用户相关联。为此,您需要告诉rails使用user_id在表中查找用户。
这就是through: :comment_likes, class: 'User'
所做的。
编辑2
检查源代码以查看更多选项: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many
答案 1 :(得分:0)
1)如果在控制器中声明了like
变量,它应该是全局的:@like
2)不要使用User.find(comment.user_id).name
或User.find(like.user_id).name
。
像comment.user.name
,@like.user.name
答案 2 :(得分:0)
简短的回答
在您的控制器中,更改
comment_like = current_user.comment_likes.build(comment: @comment)
if comment_like.save
与
@comment_like = current_user.comment_likes.build(comment: @comment)
if @comment_like.save
在您看来,更改
<%= User.find(like.user_id).name %>
与
<%= @comment_like.user.name %>