0

我有一个基本的 .each 评论声明,在它们的底部是一个添加新评论的表格。目标很简单,但我已经尝试了很多,但无法让它发挥作用。当有人在表单中提交评论时,我希望该评论显示在上方,并使用 jQuery 将表单向下移动。这工作正常,但我有两个问题。

  1. 我需要 jQuery 显示的新注释来继承一个名为 triangle-right 的 CSS 类。

  2. 我需要清除表格,它会在提交后保留最后一条评论。

这是jQuery。同样,我需要 @comment.recommendation 使用 CSS 类 triangle-right 显示并清除表单。#newrec 是表格。

$('#newrec').before('<%= escape_javascript(@comment.recommendation) %>');

如果有帮助,这里是视图。

<% recs.each do |r| %>
    <% name = User.find_by(:id => r.user_id)%>

    <p class = "triangle-right" id ="comment_<%=r.id%>">
      <b><%=name.first_name.capitalize %> <%=name.last_name.capitalize %></b>:    <%=r.recommendation %></br></br>

    <%= link_to '<i class="icon-edit"></i>'.html_safe, edit_comment_url(r),class:"btn btn-warning" if current_user.present? && r.user_id == current_user.id %>

    <%= link_to '<i class="icon-trash"></i>'.html_safe, comment_url(r), class:"btn btn-danger", method: 'delete', remote: true if current_user.present? && r.user_id == current_user.id %>

    </p>
  <%end%>
    <!-- LIST OF RECOMMENDATIONS IS ABOVE -->
    <!-- FORM FOR RECS BELOW -->
  <div>
    <%= form_tag(commentpost_url, id: "newrec", method: 'post', remote: true) do %>
      <h4><%= "Give your recommendations:" if current_user.present? %></h4>
      <%= text_area_tag :recommendation, nil, class: "rectextarea", id: "new_rec" if current_user.present? %>
      <%= hidden_field_tag :trip_detail_id, d.id %>
      <%= hidden_field_tag :user_id, current_user.id if current_user.present?%>

    <div>
      <% if current_user.present? && @trip.userid == current_user.id %>
        <%= submit_tag 'Add Comment', class: "btn btn-large btn-success" if current_user.present? %>
      <%else%>
        <%= submit_tag 'Submit Recs!', class: "btn btn-large btn-success" if current_user.present? %>
      <%end%>
    </div>
   <% end %>

最后是控制器

def create
@comment = Comment.new
@comment.recommendation = params[:recommendation]
@comment.trip_detail_id = params[:trip_detail_id]
@comment.user_id = params[:user_id]

if @comment.save

  respond_to do |format|
   format.html { redirect_to :back, notice: 'Rec was successfully created.' }
   format.json { render action: 'show', status: :created, location: @comment }
   format.js
  end

else
  render 'new'
end

结尾

谢谢!

4

1 回答 1

0

解决方案是:

  1. 如果你想添加新的评论来显示,评论应该是一个列表,。对此进行相应的修改。
  2. 提取您的评论显示部分,该<li>部分变成一个部分。
  3. 将表单部分提取为部分
  4. 渲染这些部分视图模板以替换以前的部分。
  5. 在 js 中再次渲染这两个部分

像这样的伪js代码

$('ul#comments').append('<%=j render partial: "comment", locals: {comment: @comment}')
$('#comment_form').html('<%=j render partial: "comment_form", 
                                              locals: {comment: Comment.new)') 

PS您的代码确实需要改进。太多的逻辑和太多非常规的东西。

于 2013-09-20T19:19:13.347 回答