我试图弄清楚这个 ajax 回调业务,并且没有任何运气让它工作。我看过大量的 SO 问题、教程等,但显然没有理解它是如何工作的。我正在尝试更新包含部分的 div 的内容。这是一个标准的like/unlike 类型函数,用户将点击链接,它应该通过ajax 更新图标。我的 ajax 远程请求工作正常,但我无法让回调工作。这是我的show.html.erb
文件:
<table class="v-table">
<tr>
<td>
<div class="favorite">
<%= render 'vendors/favorite' %>
</div>
</td>
<td><h2><%= image_tag @vendor.image_url %></h2></td>
<td><%= @vendor.address %></td>
</tr>
</table>
这是部分favorite
:
<% if current_user.voted_for?(@vendor) %>
<%= link_to image_tag("Heart (2).png"),
{ :controller => :vendors,
:action => 'vote_against_vendor', :vendor_id => @vendor.id},
{ :method => 'delete', :remote => true }%>
<% else %>
<%= link_to image_tag("Heart (1).png"),
{ :controller => :vendors,
:action => 'vote_for_vendor', :vendor_id => @vendor.id},
{ :method => 'post', :remote => true} %>
<% end %>
这是我的相关控制器操作:
respond_to :js
def show
@vendor = Vendor.find_by_id(params[:id])
end
def vote_for_vendor
vendor = Vendor.find(params[:vendor_id])
current_user.vote_for(vendor)
render :toggle
end
def vote_against_vendor
vendor = Vendor.find(params[:vendor_id])
current_user.unvote_for(vendor)
render :toggle
end
我的 toggle.js.erb 文件:
$("#favorite").html("<%= escape_javascript render('favorite') %>");
我对使用 js 和 ajax 真的很陌生,请帮忙!提前致谢。
错误日志
正确提交远程事务后,我收到此错误:
Rendered vendors/_favorite.html.erb (1.3ms)
Rendered vendors/toggle.js.erb (2.6ms)
Completed 500 Internal Server Error in 47ms
ActionView::Template::Error (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):
1: <% if current_user.voted_for?(@vendor) %>
2: <%= link_to image_tag("Heart (2).png"),
3: { :controller => :vendors,
4: :action => 'vote_against_vendor', :vendor_id => @vendor.id},
app/views/vendors/_favorite.html.erb:1:in `_app_views_vendors__favorite_html_erb___385976980778737159_2184308220'
app/views/vendors/toggle.js.erb:1:in `_app_views_vendors_toggle_js_erb___3800164439665893406_2169792040'
app/controllers/vendors_controller.rb:39:in `vote_for_vendor'
Rendered /Users/User/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.7ms)
Rendered /Users/User/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.3ms)
Rendered /Users/User/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (11.1ms)
不知道这意味着什么:ActionView::Template::Error (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):