ruby-on-railsrubyroutesstatic-pages

rails routes link_to specific controller action


For a simple quiz app I'm trying to connect a couple of static pages, but since I'm new to Ruby on Rails I'm having trouble with how to correctly define my routes.

I have a static page pages/user_quiz_start with this link that is supposed to send the user to pages/user_quiz_question.html and initialize the current_question_index variable:

#views/pages/user_quiz_start.html.rb:
<%= link_to 'Start Quiz!', :controller => :pages, :action => :start_quiz %>

But I get "ActionController::UrlGenerationError in Pages#show" -> No route matches {:action=>"start_quiz", :controller=>"pages", :page=>"user_quiz_start"}

Here is my controller and my routes:

#pages_controller.rb:
def show
    if valid_page?
      render template: "pages/#{params[:page]}"
    else
      render file: "public/404.html", status: :not_found
    end
  end

  def start_quiz
    if @quiz_session.start!
      redirect_to user_quiz_question_path, notice: 'Quiz has been started'
    else
      redirect_to :back, error: 'Quiz cannot be started'
    end
  end

#in the model quiz_session.rb:
def start!
    self.current_question_index = 0
end

#routes.rb:
Rails.application.routes.draw do
  ...
  get 'home/index'
  get '/user_quiz_start', :to => redirect('pages/user_quiz_start.html')
  get '/user_quiz_question' => redirect('pages/user_quiz_question.html')

  # Setup static pages
  get "/pages/:page" => "pages#show"

  devise_scope :user do
    root to: redirect('/pages/user_home')
    match '/sessions/user', to: 'devise/sessions#create', via: :post
  end

  root 'pages#home'
end

I know my routes are inconsistent and I have been looking at various guides concerning routes in rails, but I just don't get it yet :/ Any help would be appreciated.


Solution

  • "ActionController::UrlGenerationError in Pages#show" -> No route matches {:action=>"start_quiz", :controller=>"pages", :page=>"user_quiz_start"}

    Problem:

    You don't have a route for start_quiz action of pages_controller in your config/routes.rb file

    Solution:

    Add this entry in routes.rb

    get "/pages/start_quiz" => "pages#start_quiz"
    

    And now the route will take you to the start_quiz action in pages_controller