所以我有一个应用程序,用户可以在其中制作个人资料,参加活动和评论活动。我遇到的问题是:例如:当用户A发表评论,而用户B发表评论时,用户在其各自的评论旁边都有用户A的profile_image。
这是帮助我更清楚的代码:
events_controller.rb snippit
def create
@event = current_user.events.new(event_params)
respond_to do |format|
if @event.save
format.html { redirect_to :back, notice: 'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: @event }
format.js
else
format.html { render action: 'new' }
format.json { render json: @event.errors, status: :unprocessable_entity }
format.js
end
end
end
def show
@event = Event.find(params[:id])
@commentable = @event
@user = User.find(params[:id])
@comment = @event.comments.new
end
_comment.html.erb(在events / show.html中部分呈现)
<div class="comment">
<%= simple_user_avatar(@user) %> <%= comment.user.name %> (<small><%= time_ago_in_words(comment.created_at) + " ago" %></small>):<br /><br />
<div><%= simple_format comment.body %></div>
</div>
helpers.rb中的simple_user_avatar帮助方法
def simple_user_avatar(user)
if user.profile_image.present?
html = link_to (image_tag user.profile_image_url(:small).to_s), user
else
html = link_to (image_tag "profile-placeholder1.png", size: '50x50'), user
end
return html
end
我做错了什么?如何在每个用户的评论旁边显示他们自己的个人profile_image,而不是每个发表评论的用户都在他们的评论旁边有用户A的profile_image。
答案 0 :(得分:0)
正如Kien Thanh指出的那样,您使用了错误的用户来显示个人资料图片。此外,您的EventsController似乎有不正确的显示操作。您正在使用相同的参数[:id]来搜索用户和事件。如果您有一个嵌套路由,其中:users资源嵌套在:events resources下,那么您的show action将是:
def show
@event = Event.find(params[:event_id])
@commentable = @event
@user = User.find(params[:id])
@comment = @event.comments.new
end
评论部分中的simple_user_avatar代码应为:
<%= simple_user_avatar(comment.user) %>
您希望获得发表评论的用户并将其传递给simple_user_avatar帮助程序,以便根据评论的用户更改个人资料照片。