问题
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