Martin Rails Martin Rails - 2 months ago 5
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

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])
# Here is where I struggle,
#if User haven't got already a match in the DB (Join table User_ID / Game_ID) then : << game
flash[:notice] = "#{} Favorited"
redirect_to games_url
flash[:notice] = "#{} already favorited"
redirect_to games_url

Thanks a lot in advance.


Has Game has_many :game_users? If so should be enough

if game.game_users.exists?(user_id: 

note that you can do it even without association

if GameUser.exists?(user_id:, game_id: