我正在尝试进行ajax调用,但由于模板错误而获得500 (Internal Server Error)
。这是我在服务器日志中获得的内容:
ActionView::Template::Error (undefined local variable or method `dish' for #<#<Class:0x007fcd62f1b008>:0x007fcd6516bab8>):
1: <% if current_user.liked? dish %>
2: <%= link_to "Unlike", unlike_restaurant_dish_path(@restaurant, dish), method: :put, remote: true %>
3: <% else %>
4: <%= link_to "Like", like_restaurant_dish_path(@restaurant, dish), method: :put, remote: true %>
app/views/restaurants/dish_partials/_like_toggle.html.erb:1:in `_app_views_restaurants_dish_partials__like_toggle_html_erb___2598971629205628451_70260057733340'
app/views/dishes/like.js.erb:1:in `_app_views_dishes_like_js_erb__1312876563634492607_70260057701620'
app/controllers/dishes_controller.rb:6:in `like'
据我所知,它没有找到我在我的部分dish
块中传递的块变量each
。需要做些什么才能让他们得到认可?
菜肴控制器
class DishesController < ApplicationController
before_action :load_restaurant_and_dish, only: [:like, :unlike, :dislike, :undislike]
def like
@dish.liked_by current_user
respond_to do |format|
format.html { redirect_to @restaurant }
format.js
end
end
...
private
def load_restaurant_and_dish
@restaurant = Restaurant.find(params[:id])
@dish = Dish.find(params[:id])
end
end
视图/菜/ like.js.erb
$(".restaurant__dish").html('<%= escape_javascript(render partial: "restaurants/dish_partials/like_toggle", dish: dish) %>');
视图/餐馆/ dish_partials / _dishes.html.erb
<% @dishes.each do |dish| %>
<div class="restaurant__dish">
<b><%= dish.name %></b>
<%= render "restaurants/dish_partials/like_toggle", dish: dish %>
</div>
<% end %>
视图/餐馆/ dish_partials / _like_toggle.html.erb
<% if current_user.liked? dish %>
<%= link_to "Unlike", unlike_restaurant_dish_path(@restaurant, dish), method: :put, remote: true %>
<% else %>
<%= link_to "Like", like_restaurant_dish_path(@restaurant, dish), method: :put, remote: true %>
<% end %>
<% if current_user.disliked? dish %>
<%= link_to "Undislike", undislike_restaurant_dish_path(@restaurant, dish), method: :put, remote: true %>
<% else %>
<%= link_to "Dislike", dislike_restaurant_dish_path(@restaurant, dish), method: :put, remote: true %>
<% end %>
答案 0 :(得分:1)
<强>视图/菜/ like.js.erb 强>
$(".restaurant__dish").html('<%= escape_javascript(render "restaurants/dish_partials/like_toggle", dish: @dish) %>');
或
$(".restaurant__dish").html('<%= escape_javascript(render partial: "restaurants/dish_partials/like_toggle", locals: { dish: @dish }) %>');
您在菜变量之前缺少 @ 。