Voting for nested objects using the Acts As Votable gem

[亡魂溺海] 提交于 2019-12-04 20:16:45

A number of things needed to be done to get this to work. The first order of business was moving my controller action to my dishes controller. I also added two more actions: unlike and undislike for toggle functionailty.

NOTE: Logic for authenticating non-registered for users to liking/disliking dishes would still need to be written but this should help get you started.

Dishes Controller

class DishesController < ApplicationController
  before_action :load_restaurant_and_dish, only: [:like, :unlike, :dislike, :undislike]

  def like
    @dish.liked_by current_user
    redirect_to @restaurant
  end

  def unlike
    @dish.unliked_by current_user
    redirect_to @restaurant
  end

  def dislike
    @dish.disliked_by current_user
    redirect_to @restaurant
  end

  def undislike
    @dish.undisliked_by current_user
    redirect_to @restaurant
  end

  private
    def load_restaurant_and_dish
      @dish       = Dish.find(params[:id])
      @restaurant = @dish.restaurant
    end
end

Next was configuring my routes to correspond with my restaurant and dish models:

Routes

resources :restaurants do
  resources :dishes, only: [:like, :unlike, :dislike, :undislike] do
    member do
      put "like",      to: "dishes#like"
      put "unlike",    to: "dishes#unlike"
      put "dislike",   to: "dishes#dislike"
      put "undislike", to: "dishes#undislike"
    end
  end
end

I ended up refactoring my show view and created a few partials to reduce clutter now that there's a little bit of logic involved:

Restaurants - Show View

...
<%= render "restaurants/dish_partials/dishes" %>
...

Dishes Partial

<% @dishes.each do |dish| %>
  <div>
    <h2><%= dish.category_name %></h2>

    <span><b><%= dish.name %></b></span>

    <%= render "restaurants/dish_partials/like_toggle", dish: dish %>
  </div>
<% end %>

Like Toggle Partial

<% if current_user.liked? dish %>
    <%= link_to "Unlike", unlike_restaurant_dish_path(@restaurant, dish), method: :put %>
<% else %>
    <%= link_to "Like", like_restaurant_dish_path(@restaurant, dish), method: :put %>
<% end %>   

<% if current_user.disliked? dish %>
    <%= link_to "Undislike", undislike_restaurant_dish_path(@restaurant, dish), method: :put %>
<% else %>
    <%= link_to "Dislike", dislike_restaurant_dish_path(@restaurant, dish), method: :put %>
<% end %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!