I'm working on an app where you can add games to a library and also remove them. I have the adding function working via clicking a button, however my if statement to bring up "remove from library" is not showing.
Here is my library method in my games controller which controls the add/remove feature:
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
In the view an "Add to Library" button is supposed to appear on games that aren't in your library, and if it is in your library it should switch to "Remove from Library"
<% 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 %>
The action determined by user_added_to_library? isn't working so I always see the Add to Library button.
Here is my helper for user_added_to_library?
module GamesHelper
def user_added_to_library? user, game
user.libraries.where(user: user, game: @game).any?
end
end
I thought maybe I needed to change libraries to library_additions but I get StatementInvalid error. The way the code is written now is not throwing up errors but it might as well not be there at all.
My User model if that's necessary:
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
Do I need to alter my user_added_to_library? method or is there another issue?
Aucun commentaire:
Enregistrer un commentaire