0

I am coding a Rails app, where I would like to show specific restaurants, hotels and bars for a specific city.

My problem is when I want to show a specific instance of a Restaurant (for now), I always end-up on the page of the Restaurant with the id 1.

Here is my routes file :

Rails.application.routes.draw do
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root to: 'cities#index'
  resources :cities, only: %i[index show] do
    resources :restaurants, only: [:show]
    resources :hotels, only: [:show]
    resources :clubs, only: [:show]
  end
end

Here my show for a specific city:

<h1><%= @city.name %></h1>

<div class="row">
  <div class="col-4">
    <h2>Restaurants</h2>

    <% @restaurants.each do |restaurant| %>
      <h3><%= link_to restaurant.name, [@city, @restaurant] %></h3>
    <% end %>
  </div>

  <div class="col-4">
    <h2>Hotels</h2>

    <% @hotels.each do |hotel| %>
      <h3><%= hotel.name %></h3>
    <% end %>
  </div>

  <div class="col-4">
    <h2>Bars</h2>

    <% @clubs.each do |club| %>
      <h3><%= club.name %></h3>
    <% end %>
  </div>
</div>

Here my Cities controller:

class CitiesController < ApplicationController
  def index
    @cities = City.all
  end

  def show
    @city = City.find(params[:id])
    @restaurants = Restaurant.all
    @hotels = Hotel.all
    @clubs = Club.all
  end
end

Here my restaurant controller:

class RestaurantsController < ApplicationController
  before_action :find_city
  before_action :set_restaurant, only: [:show]

  def index
    @restaurants = @city.restaurants
  end

  def show; end

  private

  def find_city
    @city = City.find(params[:city_id])
  end

  def set_restaurant
    @restaurant = @city.restaurants.find(params[:id])
  end
end

On the city show, whatever the Restaurant I click on, I always end up on the page of the restaurant with the id 1 and with this path: http://localhost:3000/cities/1/restaurants/1 and I really don't understand why...

I have used this tutorial to help me but I am still missing something apparently.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

0

Change this line:

<h3><%= link_to restaurant.name, [@city, @restaurant] %></h3>

to this:

<h3><%= link_to restaurant.name, restaurant %></h3>
Sean Huber
  • 3,945
  • 2
  • 26
  • 31
  • Thank you for your answer. It's still does not work though. When I use your code, it gives me this error when I click on the link : undefined method `restaurant_path' for #<#Class:0x00007ff2c13d1088:0x00007ff2c13d72f8> I really fail to see why my previous solution does not work properly... – Kevin Agoh Dec 01 '21 at 23:57