Home > other >  How to pass id in url in ruby on rails?
How to pass id in url in ruby on rails?

Time:08-11

I am new in ruby on rails and i am trying to pass id in url from one controller to another controller. And i am getting this error.

Couldn't find Tournament without an ID

And here is my code: matches View

<h2 ><%= @tournaments.id %></h2>
<h2 ><%= @tournaments.title %></h2>
<p>
    <% @players = @tournaments.player_ids %>
    Players = <%= @players.uniq %>
</p>

<div >
    <div >
        <div >
            <div >
            <div >
            </div>
            <div >
                <%= link_to "Edit", edit_tournament_path(@tournaments), class: "btn btn-outline-info" %>
                <%= link_to "Delete", tournament_path(@tournaments), method: "delete", class: "btn btn-outline-danger", data: {confirm: "Are you sure you want to delete?"} %>
            </div>
        </div>
    </div>
    <p><%= link_to "All Tournaments", root_path, class: "btn btn-outline-primary float-right" %></p>
    <p><%= link_to "Schedules", matches_path(@touraments), class: "btn btn-outline-primary float-right" %></p>
</div>

This is my another controller where i want this data:

class MatchesController < ApplicationController
    def index
        @match = Tournament.find(params[:id])
    end
end

CodePudding user response:

I'll advise you to check your params before assignation. I'm almost sure that you'll find something like

#<ActionController::Parameters {"controller"=>"matches", "action"=>"index", "tournament_id"=>"666"} permitted: false>

Which means you simple need to adjust your controller with:

class MatchesController < ApplicationController
    def index
        @match = Tournament.find(params[:tournament_id])
    end
end

CodePudding user response:

An index route does not accept an id by default, so actually Rails will be interpreting the tournament id as a format and creating a URI like /matches.13 based on your code.

Instead you need to actually pass it as a parameter like this: matches_path(tournament_id: @tournaments) and then in your controller it will be available as params[:tournament_id]

  • Related