Rails 4:在索引操作上发布和评论ajax

时间:2014-03-15 15:23:46

标签: javascript jquery ruby-on-rails ruby ajax

我尝试在我的索引操作中创建一个简单的Post / Comment函数,但我也尝试在ajax中执行它(目前,在Comment上,但是我收到此错误:          ActionView :: Template :: Error(未定义的局部变量或方法`comment'

这是我的文件:

comments_controller.rb

    def create
      @posts = Post.includes(:comments).order("created_at DESC")
      @comment = current_user.comments.new(comment_params)
       respond_to do |format|
        if @comment.save
       format.js {render 'posts/create'}
        else
       redirect_to :back
        end
      end
     end

index.html.erb

  <% @posts.each do |post| %>
  <tr>
    <td><%= post.user.email %></td>
    <td><%= post.content %></td>

    <% post.comments.each do |comment| %>
    <div id="comment">
      <%= render :partial => 'comment_ajax', :locals => { :comment => comment } %>
    </div> 
    <% end %>

    <%= form_for @comment, remote: true do |f| %>
     <%= f.text_field :content %>
     <%= f.submit %>
    <% end %>
   <% end %>

posts_controller.rb

 def index
   @posts = Post.includes(:comments).order("created_at DESC")
   @comment = Comment.new
   @post = Post.new
 end

的routes.rb

resources :posts
resources :comments

create.js.erb

 $("#comment").html("<%= escape_javascript(render :partial => 'posts/comment_ajax', :locals => { :comment => comment }) %>");

_comment_ajax.html.erb

 <%= comment.content %>

我知道这是因为我的create.js.erb文件中的“:locals =&gt; {:comment =&gt; comment}”,但我无法理解。

谢谢!

0 个答案:

没有答案