Почему этот запрос ajax заменяет все мои комментарии новым отправленным комментарием? - PullRequest
1 голос
/ 07 апреля 2011

Итак, у меня есть эта форма, которая запрашивает JS-вызов при отправке комментария:

<%= simple_form_for([@video, @video.comments.new], :remote => true) do |f| %>
  <%= f.association :comment_title, :collection => @video.comment_titles, :label => "Comment Title:", :include_blank => false %>
  <%= f.input :body, :label => false, :placeholder => "Post a comment." %>
  <%= f.button :submit, :value => "Post" %>
<% end %>

Вызывает это действие создания в контроллере комментариев:

def create
  @comment = @video.comments.new(params[:comment].merge({:user_id => current_user.id}))
  if @comment.save
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    end
  else
    respond_to do |format|
      format.html { redirect_to :back, :alert => "Unable to add comment." }
      format.js { render 'fail_create.js.erb' }
    end
  end
end

, который отображает этот файл create.js.erb:

$(".comment_content").html('<%= escape_javascript(render(@comment)) %>');
$(".comment_form")[0].reset();

Приведенный выше файл create.js.erb отображает частичный комментарий в этот файл:

<% comment_title.comments.each do |comment| %>
     <div class="comment_content">
        <%= render comment %>
     </div>
<% end %>

Почему все мои комментарии заменяются вновь представленными комментариями в этом запросе AJAX?

Вот мой частичный комментарий:

<%= link_to image_tag(comment.user.profile.photo.url(:tiny)), profile_path(comment.user.profile), :class => "comment_image" %>
<div class="textual_comment_content">
    <div class="comment_text">
        <span class="name_link">
            <%= link_to "#{comment.user.name}", profile_path(comment.user.profile), :class => "normal" %>
        </span>
        <%= comment.body.gsub("'",'&apos;').html_safe %>
    </div>
    <span class="comment_footer">
        <ul>
            <li class="list_style"><%= time_ago_in_words(comment.created_at) %> ago</li>
            <% unless current_user != comment.user %>
            <li><%= link_to "Delete", video_comment_path(:video_id => @video, :id => comment), :method => :delete, :class => "normal" %></li>
            <% end %>
        </ul>
     </span>
 </div>

1 Ответ

3 голосов
/ 08 апреля 2011

first Вам нужно переместить обтекание div из первого кода в партиал:

<div class="comment_content">
</div>

, а затем просто вставить HTML до / после первого / последнего элемента:

$(".comment_content:first").before('<%= escape_javascript(render(@comment)) %>');
$(".comment_content:last").after('<%= escape_javascript(render(@comment)) %>');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...