Martin Rails Martin Rails - 3 months ago 11
MySQL Question

Rails - Statement IF for a join table in the controller


I would like an advice on the "IF" statement about an action "Favorite" which permit to the user to favorite a game.
One association is necessary for one game. One user ID / One Game ID (in the join table).

I got the unicity in the DB with my model GameUser:

class GameUser < ActiveRecord::Base
belongs_to :game
belongs_to :user
validates_uniqueness_of :game_id, scope: :user_id
end


Controller (which is working, just return an error when I got already favorited the game):
I would like to write correctly the If and I dont really know how

def favorite
game = Game.find(params[:id])
if
# Here is where I struggle,
#if User haven't got already a match in the DB (Join table User_ID / Game_ID) then :
current_user.games << game
flash[:notice] = "#{Game.name} Favorited"
redirect_to games_url
else
flash[:notice] = "#{Game.name} already favorited"
redirect_to games_url
end
end


Thanks a lot in advance.

Answer

Has Game has_many :game_users? If so should be enough

if game.game_users.exists?(user_id: current_user.id) 

note that you can do it even without association

if GameUser.exists?(user_id: current_user.id, game_id: game.id)