在lib文件夹模块中使用url_for

时间:2011-05-03 20:54:50

标签: ruby-on-rails ruby-on-rails-3

我有一个名为“type”的字段和一个名为“value”的字段的模型。类型字段将确定在呈现之前如何解析“值”。我希望这很容易扩展,所以我在我的lib文件夹中放了各种“格式化程序”类。

我的一个“格式化程序”调用了url_for:

class CustomTypeFormatter 
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers

  def show
    raw sanitize( auto_link( value ) )
  end

  def get_url(page)
    url_for( :controller => :my_controller, :action => :show, :path => page.path )
  end

end

问题是,url_for引发了这个错误:

undefined local variable or method `_routes'

我想我只是错过了一个包含。有谁知道它应该是什么?

**更新* * *

这是堆栈跟踪的一部分:

actionpack (3.0.7) lib/action_dispatch/routing/url_for.rb:131:in `url_for'
actionpack (3.0.7) lib/action_view/helpers/url_helper.rb:99:in `url_for'

所以我认为它必须是一些ActiveDispatch依赖,虽然我无法弄清楚

2 个答案:

答案 0 :(得分:17)

胜利!

include ActionView::Helpers
include ActionDispatch::Routing
include Rails.application.routes.url_helpers

通过http://apidock.com/rails/ActionController/UrlWriter

答案 1 :(得分:0)

可以使用Rails.application.routes.url_helpers替代url_for,只需添加路由:as即可,如下例所示:

get "sessions/destroy/:param_id", as: :logout 

因此您可以按以下方式使用它:

Rails.application.routes.url_helpers.logout_path(:param_id => your_value)

这与url_for

相同

希望这会有所帮助