ruby-on-railsrubyinfo

Create info page for each restaurant with Ruby on Rails


I am trying to create an info page for each restaurant in a Ruby on rails app. I created an action info in Restaurant controller and added a line in routes.rb. but it gives an error

"ActiveRecord::RecordNotFound in RestaurantsController#info" Couldn't find Restaurant with 'id'=..

What is wrong with my code?

This is my Restaurant controller:

class RestaurantsController < ApplicationController
 before_action :set_restaurant, only: [:show, :edit, :update, :destroy, :info]

  def info
  end 

  private
  def set_restaurant
    @restaurant = Restaurant.find(params[:id]) 
  end
end

This is my routes.rb:

Rails.application.routes.draw do

 resources :restaurants do 
  get '/info', to: 'restaurants#info'
 end

end

And this a link to restaurant info page:

<%= link_to 'Info', restaurant_info_path(@restaurant) %> 

Solution

  • ActiveRecord::RecordNotFound in RestaurantsController#info

    By having the custom route nested inside the resources :restaurants, generates the route with wrong keys. When you run rake routes, you can see this route

    restaurant_info GET  /restaurants/:restaurant_id/info(.:format)  restaurants#info
    

    So this route has :restaurant_id not :id. So you cannot do params[:id] to fetch the value here in this line @restaurant = Restaurant.find(params[:id]) which fails with that error. Changing params[:id] to params[:restaurant_id] should solve your problem but that is not the right solution.

    The obvious and the ideal solution would be to tweak your custom route, so it can generated like this

     restaurant_info GET  /restaurants/:id/info(.:format)  restaurants#info
    

    You can tweak your custom route to below to achieve this and not having that nested inside resources :restaurants

    get 'restaurants/:id/info', to: 'restaurants#info', as: :restaurant_info
    resources :restaurants