我有两种模式:微博和评论。微博有很多评论,评论属于微博。
首先。有一个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呈现一个提要
= 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如果提交了注释,则调用create操作。
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
endcreate.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,并将每个新的注释插入到同一个微博上。
我如何才能在micropost.id中获得create.js.erb评论的知识?
_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>发布于 2016-05-20 16:31:55
你能试一下以下几种方法吗?
在create.js.erb中:
$("#comments_for_#{@comment.micropost_id}%>").html("<%= escape_javascript(render('comments/comment')) %>");我怀疑jquery选择器有问题,您可以更容易地实现您想要的结果。
PS :您不应该依赖于部分中的实例变量。相反,通过局部变量将实例vars传递给部分。否则,您的部分不能很容易地重用。
https://stackoverflow.com/questions/37351442
复制相似问题