在 js.erb ajax 调用中传递块变量

Passing a block variable in an js.erb ajax call

我正在尝试进行 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'

据我了解,它没有找到我在我的 each 块中传递的块变量 dish。需要做什么才能被认可?

菜品控制器

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

views/dishes/like.js.erb

$(".restaurant__dish").html('<%= escape_javascript(render partial: "restaurants/dish_partials/like_toggle", dish: dish) %>');

views/restaurants/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 %>

views/restaurants/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 %>

views/dishes/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 }) %>');

您在 dish 变量之前缺少 @