2

Railsブログにajaxを追加しました。1つの投稿でしか機能しませんでしたが、次に追加した後、何か奇妙なことが起こっています。この同じページに自分の投稿のコピーがあります。

Comments_controller.rb

 class CommentsController < ApplicationController
    def create
        @posts = Post.all
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create!(params[:comment])

        respond_to do |format|
            format.html {redirect_to @post}
            format.js
        end
    end

end

index.html.erb

<%= render 'post' %>

create.js.erb

  $('.post').html("<%= escape_javascript(render("posts/post")) %>") });

_post.html.erb

 <% @posts.each do |post| %>
        <div class="post">
            <p><strong> <%= post.title %> </strong>, posted <%= post.created_at.to_date %> </p> <br />
            <%= post.content %> <br />

            <%= simple_form_for [post, post.comments.build], :remote => true do |f| %>
                <%= f.input :content %>
                <%= f.button :submit %>
            <% end %>

            <%= render :partial => 'comment', :locals => {:post => post} %>
        </div>

    <% end %>

_comment.html.erb

<div class = "comment">
  <ol>
    <% post.comments.each do |comment| %>
      <li> <%= comment.content %></li>
    <% end %>
  </ol>
</div>
4

1 に答える 1

1

する必要があります

<% @posts.each do |post| %>

そこにいる?投稿を 1 ページだけ表示している場合は、 を使用してブロック外のプロパティに簡単にアクセスできます@post。そうでない場合、私はあなたの質問を誤解しています。

于 2012-09-04T15:54:32.807 に答える