ruby-on-rails - ActionController::UrlGenerationError:没有自定义路由的路由匹配

标签 ruby-on-rails ruby ruby-on-rails-4 rspec routes

因此,我创建了一个小型模型/ Controller 来使用自定义路由来处理我的应用程序中的 token 。然而,当我运行测试(rspec)时,我会失败

相关代码

Controller

读取 token (在其他地方生成)

class TokensController < ApplicationController
  def read_token
    #do whatever this token is supposed to do (unsubscribe, confirm email, etc)
    redirect_to(root_path)
  end
end

路线

get '/ta/:uuid' => 'tokens#read_token', param: :uuid, as: 'token_action'

rake 路线产生

token_action GET    /ta/:uuid(.:format)    tokens#read_token {:param=>:uuid}

型号

包含此内容是为了表明创建链接时 token 使用的是 uuid,而不是 id

class Token < ActiveRecord::Base
  def to_param
    uuid
  end    
end

并且它在开发模式下工作! :D

但是当我运行测试时......

测试

rspec Controller 测试

require 'rails_helper'

RSpec.describe TokensController, type: :controller do
  describe "#index" do
    it "test" do
      get :read_token, uuid: "12345" #12345 is obviously not real
      expect(response).to redirect_to(root_path)
    end
  end
end

错误消息

ActionController::UrlGenerationError: 
    No route matches` {:action=>"read_token", :controller=>"tokens", :uuid=>"12345"}

我尝试了什么

嗯……几乎一切。

  • 我用尽一切办法写了路线
  • 我将 :uuid 更改为 :id 认为这可能是问题所在
  • 我尝试以不同的方式指定属性,但无济于事
  • 我尝试了 stackoverflow 上类似问题的所有解决方案

最佳答案

可以通过添加 use_route: :controller_name 来使其工作;

get :index, uuid: "12345", use_route: :tokens

但是我收到的这个错误令人困惑并且代码有异味。

最终解决方案

但是,更好的解决方案是使用正确的铁路路线资源 ( http://guides.rubyonrails.org/routing.html )

resource :vendor_registration, only: [], path: '/' do
  get :read_token, on: :member, path: '/ta/:uuid'
end

现在可以使用了;并且仍然使用相同的路径

关于ruby-on-rails - ActionController::UrlGenerationError:没有自定义路由的路由匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34960566/

相关文章:

javascript - 使用 Ajax 请求 Rails Controller 数据

javascript - 使用 JS 模板作为 Rails 部分

ruby-on-rails - 如何在 Ruby 中预填充函数的参数?

ruby - 在带有 Ruby 的 Sinatra 中使用 gzip 压缩

ruby-on-rails - 动态表对我的用例有意义吗?数据库/模型架构

ruby - 在 `Rack::Session::Pool` 上使用 `Rack::Session::Cookie`

ruby-on-rails - 修复 Rails 生成器问题 : calling same generator twice no-ops and exits 0 without running 2nd generator

ruby-on-rails-4 - 消除 500 错误

ruby-on-rails - Rails - 如何 'merge' 或将值附加到 URL 中的数组?

ruby-on-rails - 链接到域提供商网站的 Heroku 应用程序