Home > Mobile >  New action not being reached in my Ruby app
New action not being reached in my Ruby app

Time:05-09

I'm just learning Ruby on Rails and building a fairly simple app that stores info to a rake generated db. I'm trying to add a new action to the controller but I can't trigger it. There's a before_action getting triggered which shouldn't be.

class GamesController < ApplicationController
  before_action :set_entry, only: %i[ show edit update destroy ]
  before_action :authenticate_user!

  def index
  end

  def analyse
    #The function here doesnt matter, its not reaching it because its hitting the set_entry instead
    puts 'howdy'
  end
  
  private

    def set_entry
      @entry = Entry.find(params[:id])
    end
    
  end

The error I'm hitting is Couldn't find Game with 'id'=analyse", highlighting the set_entry action, which to my understanding should only be running with the show, edit, update, and destroy actions (which are also in the full controller and running fine). There are other actions in the controller (such as create and new) which don't seem to trigger that set_entry and are running just fine as expected. For example, linking to the new path takes me to /entry/new, while linking to an edit path takes me to /entry/:id/edit, which is all fine. But it keeps linking my new analyse action trying for entry/:id/analyse when I want it to go to entry/analyse.

My button to trigger it is simply:

<%= link_to "Analyse", analyse_path %>

Which is in a navbar in my application.html.erb

And here's my routes.rb:

Rails.application.routes.draw do
  resources :entry
  devise_for :users
  resources :users
  root to: "entry#index"
  get 'entry/index'
  get 'entry/analyse', as: 'analyse'
end

CodePudding user response:

First of all, add the analyse action in your set_entry before action, for example: before_action :set_entry, only: %i[ show edit update destroy analyse ] to make sure set_entry is triggered before the entry#analyse is running.

Then add a customized route to let entry#analyse action handling the requests from /entry/:id/analyse.

Rails.application.routes.draw do
  # ...
  resources :entry
  get 'entry/:id/analyse', to: 'entry#analyse', as: :analyse # here
  # ...
end

CodePudding user response:

Move all of your resources to the end of your route configuration. I am not sure why its getting tripped up but it seems something within your routes is matching analyse to your entry resource and routes within rails are matched in order. All custom routes really should come first to prevent something like a generic route catching your expected action.

Best practices also state your root to: should be at the top of the configuration since it is your most popular route generally in an application.

  • Related