Martin Rails Martin Rails - 2 months ago 6x
Ruby Question

Rails - Add games Association to users

I'm building an association between Users and Games, Users can favorite or associate Games to their profile. But I got an issue with the routes or the link (I guess, maybe its something else).

I have a join table between Users and Games :

Game_User with games ID and User ID

The association is working fine in the console when I do this.

@user = User.find(session[:user_id])
@game = Game.find(params[:id]) << @game


def favorite
game = Game.find(params[:id]) << game
flash[:notice] = 'You favorited #{}'
redirect_to games_url


get "games" => "games#index"
post "games/:id" => 'games#favorite'

And I would like to do the same with my link.

Here is the list of the games, and for each a link to favorite them :

<% if current_user %>
<% @games.each do |game| %>
<td><%= %></td>
<td><%= game.plateform %></td>
<td><%= game.typegame %></td>
<td><%= link_to 'Show', game %></td>
<td><%= link_to 'Edit', edit_game_path(game) %></td>
<td><%= link_to 'Destroy', game, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td> <%= link_to "favorite", games_path, type: "favorite", method: :post %> </td>
<% end %>
<% end %>

My problem is : Creating the association between user and game(s) , when i click on the link Favorite, it's generating a new Game (def create ... )


You're calling games_path in your link_to method, but that will give you games#create instead of favorite. You need to tell Rails what name you'd like to use, with a named route: post "games/:id/" => 'games#favorite', as: :favorite_game and use favorite_game_path(game) in your view.