现在我有一个喜欢按钮,让你喜欢食物。当你尝试与食物不同时,我会收到这个错误:
The action 'destroy' could not be found for UsersController
我不确定为什么要在用户控制器中查找destroy动作。我唯一的猜测是因为按钮在用户显示页面上,所以我认为它默认为该控制器,但我如何从我的投票控制器访问删除方法?
Shared like form
<% unless current_user.votes.empty? || current_user.votes.pluck(:food_id).include?(food.id) %>
<%= form_for @vote do |f| %>
<%= f.hidden_field 'food_id', food.id %>
<%= f.hidden_field 'user_id', food.user.id %>
<%= f.submit "Vote", :class => "like_button" %>
<% end %>
<% else %>
<% vote = food.votes.where(user_id: current_user.id).first %>
<div class="unlike_button">
<%= button_to "Unlike", vote, method: :delete %>
</div>
<% end %>
class VotesController < ApplicationController
def index
@votes = Vote.all
end
def new
@vote = Vote.new
end
def create
@vote = Vote.new(vote_params)
if @vote.save
puts @vote
flash[:notice] = "Thanks for voting!"
redirect_back(fallback_location: root_path)
else
puts "No"
flash[:notice] = "Something went wrong"
redirect_back(fallback_location: root_path)
end
end
def destroy
@vote = Vote.find(params[:id])
if @vote.destroy!
flash[:notice] = "Unvoted!"
redirect_back(fallback_location: root_path)
end
end
private
def vote_params
params.require(:vote).permit(:food_id, :user_id)
end
end
class Vote < ApplicationRecord
belongs_to :user
belongs_to :food
end