为评论创建部分 rails
Creating a partial rails for comments
我的主题与 问题非常相似,只是我的评论显示在 bootstrap 模态框内。我需要创建一个评论部分,以便我可以使用 respond_to |format| do
format.js
来呈现部分并更新模态中的评论。
问题 #1。如何创建部分评论?这是代码:
CommentsController
def create
@photo = Photo.find(params[:photo_id])
@comment = @photo.comments.build(comment_params)
@comment.save
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
UsersController
def show
@user = User.find(params[:id])
@photos = @user.photos.order('created_at desc').paginate(page: params[:page], per_page: 12)
end
Users/show.html.erb
<% @photos.in_groups_of(3, false).each do |group| %>
<div class="row instagram">
<% group.each do |photo| %>
<a data-toggle="modal" href=<%="#"+"#{photo.id}"%>>
<%= image_tag(photo.picture.ad.url, class: "img-responsive")%>
</a>
<div class="modal" id=<%="#{photo.id}"%> tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
.
.
<div class="col-sm-4">
<div class="instacomments">
<% photo.comments.each do |comment| %>
<p class="commentblock">
<%= link_to comment.user.name, user_path(comment.user_id)%><span> </span><%= comment.content %>
</p>
<% end %>
</div>
</div>
在你的show.html.erb
中:
<%= render partial: "comments/comment", collection: photo.comments, as: :comment %>
请注意,as: :comment
键用于设置视图中每个集合项的局部变量名称。
所以现在您可以在 comments/_comment.html.erb
中引用 comment
变量:
<p class="commentblock">
<%= link_to comment.user.name, user_path(comment.user_id)%>
<span> </span> <!-- Not sure why you have an empty <span> here -->
<%= comment.content %>
</p>
我的主题与 respond_to |format| do
format.js
来呈现部分并更新模态中的评论。
问题 #1。如何创建部分评论?这是代码:
CommentsController
def create
@photo = Photo.find(params[:photo_id])
@comment = @photo.comments.build(comment_params)
@comment.save
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
UsersController
def show
@user = User.find(params[:id])
@photos = @user.photos.order('created_at desc').paginate(page: params[:page], per_page: 12)
end
Users/show.html.erb
<% @photos.in_groups_of(3, false).each do |group| %>
<div class="row instagram">
<% group.each do |photo| %>
<a data-toggle="modal" href=<%="#"+"#{photo.id}"%>>
<%= image_tag(photo.picture.ad.url, class: "img-responsive")%>
</a>
<div class="modal" id=<%="#{photo.id}"%> tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
.
.
<div class="col-sm-4">
<div class="instacomments">
<% photo.comments.each do |comment| %>
<p class="commentblock">
<%= link_to comment.user.name, user_path(comment.user_id)%><span> </span><%= comment.content %>
</p>
<% end %>
</div>
</div>
在你的show.html.erb
中:
<%= render partial: "comments/comment", collection: photo.comments, as: :comment %>
请注意,as: :comment
键用于设置视图中每个集合项的局部变量名称。
所以现在您可以在 comments/_comment.html.erb
中引用 comment
变量:
<p class="commentblock">
<%= link_to comment.user.name, user_path(comment.user_id)%>
<span> </span> <!-- Not sure why you have an empty <span> here -->
<%= comment.content %>
</p>