【发布时间】:2020-11-23 10:05:19
【问题描述】:
我正在开发一个应用程序,您可以在其中将游戏添加到库中并删除它们。我有通过单击按钮来工作的添加功能,但是我没有显示“从库中删除”的 if 语句。
这是我的游戏控制器中控制添加/删除功能的库方法:
def library
type = params[:type]
game = Game.new(game_params)
game.fetch_data
if type == "add"
current_user.library_additions << game
redirect_to user_library_path(current_user), notice: "Game was added to your library"
elsif type == "remove"
current_user.library_additions.delete(game)
redirect_to root_path, notice: "Game was removed from your library"
else
# Type missing, nothing happens
redirect_to game_path(game), notice: "Looks like nothing happened. Try once more!"
end
在视图中,“添加到库”按钮应该出现在您的库中没有的游戏上,如果它在您的库中,它应该切换到“从库中删除”
<% if user_added_to_library?(current_user, game) %>
<button type="button"><%= link_to 'Remove from library', add_game_path(game.id, type: "remove", game: game), method: :put %> </button>
<% else %>
<button type="button"> <%= link_to 'Add to library', add_game_path(game.id, type: "add", game: game), method: :put %> </button>
<% end %>
user_added_to_library 决定的动作?不工作,所以我总是看到“添加到库”按钮。
这是我的 user_added_to_library 助手?
module GamesHelper
def user_added_to_library? user, game
user.libraries.where(user: user, game: @game).any?
end
end
我想也许我需要将库更改为 library_additions,但我收到 StatementInvalid 错误。现在编写代码的方式不会抛出错误,但它可能根本不存在。
如有必要,我的用户模型:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :games
has_many :libraries
has_many :library_additions, through: :libraries, source: :game
end
我需要更改我的 user_added_to_library 吗?方法还是有其他问题?
【问题讨论】:
标签: ruby-on-rails if-statement helper