【问题标题】:rails routes link_to specific controller actionrails 路由 link_to 特定的控制器动作
【发布时间】:2017-04-25 18:41:52
【问题描述】:

对于一个简单的测验应用程序,我正在尝试连接几个静态页面,但由于我是 Ruby on Rails 的新手,我在如何正确定义我的路线方面遇到了麻烦。

我有一个带有此链接的静态页面 pages/user_quiz_start,它应该将用户发送到 pages/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=&gt;"start_quiz", :controller=&gt;"pages", :page=&gt;"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

我知道我的路线不一致,我一直在查看有关 Rails 路线的各种指南,但我还不明白:/ 任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby routes static-pages


    【解决方案1】:

    "ActionController::UrlGenerationError in Pages#show" -> 没有路由匹配 {:action=>"start_quiz", :controller=>"pages", :page=>"user_quiz_start"}

    问题:

    您的 config/routes.rb 文件中没有 pages_controllerstart_quiz 操作的路由

    解决方案:

    在 routes.rb 中添加这个条目

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

    现在路线将带您到pages_controller 中的start_quiz 操作

    【讨论】:

    • 谢谢!这是有道理的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    相关资源
    最近更新 更多