Using the respond_to method to render a js.erb partial

寵の児 提交于 2019-12-23 04:18:32

问题


I have a feature where users like/unlike and dislike/undislike dishes. This is how I initially have my actions setup:

Dishes Controller

class DishesController < ApplicationController
  def like
    @dish.liked_by current_user
  end

  def dislike
    @dish.disliked_by current_user
  end
  ...
end

Considering the js.erb templates for each template are completely identical I wanted to create just one shared partial that each could use:

Original Setup

# like.js.erb, unlike.js.erb,dislike.js.erb,undislike.js.erb

$(".restaurant__dish-vote--<%= @dish.modifier_class %>").html('<%= escape_javascript(render "restaurants/menu_partials/dish_votes", dish: @dish) %>');

New Setup

# shared/_vote.js.erb

$(".restaurant__dish-vote--<%= @dish.modifier_class %>").html('<%= escape_javascript(render "restaurants/menu_partials/dish_votes", dish: @dish) %>');

Now I'm trying to refactor my controller to reflect these changes but the ajax functionality doesn't seem to work with the following:

class DishesController < ApplicationController
  def like
    respond_to do |format|
      format.js { render partial: "dishes/shared/vote.js.erb" }
    end

    @dish.liked_by current_user
  end
end

The action completes but the changes on the user-facing side are only reflected upon refresh. What am I doing wrong?


回答1:


I think you should call @dish.liked_by current_user before render partial: "dishes/shared/vote.js.erb". The problem is that @dish is not updated yet.



来源:https://stackoverflow.com/questions/31790349/using-the-respond-to-method-to-render-a-js-erb-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!