Bad Programmer
Bad Programmer

Reputation: 962

Method Being Invoked Before An Action Even When before_action Not Set

I have an action that takes the input of a form, and then does some comparisons and database updates. Afterwards, it redirects to another action.

This works fine if the users are following the flow of the form, but I also want to enable users to access the results action directly, by going to controller/results. Right now this throws an error:

Couldn't find Preference with 'id'=result

The error is because it is trying to invoke the set_preferences() method. However, that method does not get called before the results action.

How can I update this s that users can navigate to controller/results directly and an id parameter is not required?

Here is the current flow: index->new->create->test->results

class PreferencesController < ApplicationController
  before_action :set_preference, only: [:show, :edit, :test, :update, :destroy]

  def test
    #stuff happens

    #redirect to results exploration page
    render action: "results"#
  end

  def results
    @results = Preference.all
  end

Upvotes: 0

Views: 64

Answers (1)

coorasse
coorasse

Reputation: 5528

That's because is executing the show action. If you check the logs you will see that PreferencesController#show is invoked. Since is not a REST method you need to define it in the routes.rb file. Something like:

resources :preferences do
  get :results, on: :collection
end

in order to have GET /preferences/results to invoke the correct action.

Upvotes: 2

Related Questions