AJAX按钮不工作Rails

AJAX Fave Button Not Working Rails

本文关键字:Rails 工作 按钮 AJAX      更新时间:2023-09-26

我试图让用户喜欢的帖子,然后它通过AJAX向他们展示某种交互,但它不工作。

我在控制台得到的错误是:

ActionView::Template::Error (undefined local variable or method `post_item' for #<#<Class:0x007fecb2a3d5f8>:0x007fecb2a357e0>):

按钮正在通过局部渲染:

<%= render "shared/fave_form", post_item: post_item %>
下面是按钮(shared/_fave_form.html.erb)的代码:
<% if current_user.voted_on?(Post.find(post_item)) %>
     <%= link_to "unlike", vote_against_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% else %>
     <%= link_to "like", vote_up_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% end %> 

这是toggle.js.erb文件:

 $("#fave").html("<%= escape_javascript render('fave_form') %>");

当您使用toggle.js.erb渲染部分时,它不会获得localspost_item,您也必须提供它。所以,你的js代码应该像下面这样

$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: post_item}).html_safe %>);

我猜你正在使用一些ajax调用,然后你的toggle.js.erb,所以在你的toggle的行动,你必须指定值post_item,让它的实例变量@post_item,以便我们可以使用它在toggle.js.erb

$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: @post_item}).html_safe %>);

局部使用了一个局部变量,所以传递post_item作为局部变量:

<%= render :partial => "shared/fave_form", :locals => {post_item: post_item} %>