我有两个型号; Micropost和评论。 Micropost有很多评论,评论属于Micropost。
首先。有一个StaticPagesController可以保存我的主页操作
class StaticPagesController < ApplicationController
def home
if logged_in?
@micropost = current_user.microposts.build
@feed_items = current_user.microposts.paginate(page: params[:page])
end
end
(..)
home.html.erb
呈现Feed
= render 'shared/feed'
_feed.html.haml
呈现feed_items
- if @feed_items.any?
%ol.microposts
= render @feed_items
= will_paginate @feed_items
呈现_micropost.html.haml
%li
%div.comments{data: { mid: "#{micropost.id}"}}
%div.comment_container{:id => "comments_for_#{micropost.id}"}
%ul
- comments = micropost.comments
- comments.each do |comment|
%li
%a{:href => user_path(comment.user), :class => "author"}
= comment.user.name
%span.comment_body= comment.body
%span.comment_timestamp= "created " + time_ago_in_words(comment.created_at).to_s
%div
= form_for current_user.comments.build(:micropost_id => micropost.id), |
:remote => true do |f|
= f.hidden_field :micropost_id
= f.hidden_field :user_id
= f.text_field :body, class: "form-control", placeholder: "What do you think?"
= button_tag(type: 'submit', class: "btn btn-default") do
%i.glyphicon.glyphicon-comment
Comment
如果提交了评论,则称为创建操作
class CommentsController < ApplicationController
before_action :correct_user, only: :destroy
def create
@micropost = Micropost.find(params[:comment][:micropost_id])
@comments = @micropost.comments
@comment = current_user.comments.build(comment_params)
@comment.save
respond_to do |format|
format.js
format.html
end
private
def comment_params
params.require(:comment).permit(
:id, :body, :user_id, :micropost_id)
end
def correct_user
@comment = current_user.comments.find_by(id: params[:id])
redirect_to root_url if @comment.nil?
end
end
create.js.erb
var mid = $(".comment_container").parent(".comments").data('mid');
$("#comments_for_" + mid).html("<%= escape_javascript(render('comments/comment')) %>")
我的目标是在不重新加载整个页面的情况下为其相关微博添加新评论。
我把micropost.id放到%div.comments{data: { mid: "#{micropost.id}"}}
的标记处,我试图通过其父标签捕获微博
最后(重新)使用部分
但这会返回相同的id,并在同一个微博中插入每个新评论。
如何在create.js.erb
中了解评论的micropost.id?
_comment.html.erb
<ul>
<% @comments.each do |comment| %>
<li>
<a class="author" href="<%= user_path(comment.user) %>">
<%= comment.user.name %>
</a>
<span class="comment_body">
<%= comment.body %>
</span>
<span class="comment_timestamp">
<%= "created " + time_ago_in_words(comment.created_at).to_s %>
</span>
</li>
<% end %>
</ul>
答案 0 :(得分:1)
您可以尝试以下方法:
在create.js.erb
:
$("#comments_for_#{@comment.micropost_id}%>").html("<%= escape_javascript(render('comments/comment')) %>");
我怀疑你的jquery选择器出了问题,你可以更轻松地实现你想要的东西。
PS:您不应该依赖部分中的实例变量。相反,通过本地传递您的实例变量到部分。否则你的部分不能轻易重复使用。