2017-04-25 33 views
0

對於一個簡單的測驗應用程序,我試圖連接幾個靜態頁面,但由於我是Ruby on Rails的新手,我在如何正確定義我的路線時遇到了問題。rails routes link_to特定的控制器動作

我有一個靜態頁面頁/ user_quiz_start這個鏈接是應該向用戶發送到頁/ user_quiz_question.html並初始化變量current_question_index:

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

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

這裏是我的控制器和我的路線:

#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 

我知道我的路線是不一致的,我一直在尋找有關軌道的各種指南,但我只是不明白:/任何幫助,將不勝感激。

回答

0

「的ActionController :: UrlGenerationError在頁面#秀」 - >沒有路由匹配{:動作=> 「start_quiz」:控制器=> 「頁」,頁面=> 「user_quiz_start」}

問題:

你不必在你的config/routes.rb文件的pages_controllerstart_quiz行動路線

解決方案:

添加此項在routes.rb中

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

而現在的路線將帶你到start_quiz行動pages_controller

+0

謝謝!這就說得通了 :) – megahra