简体   繁体   English

如何在rails 3中定义自己的路由助手?

[英]How to define own routing helpers in rails 3?

I use polimorphic_path and it some buggy.我使用 polimorphic_path 并且它有一些错误。 This method require some route helper that not defined.此方法需要一些未定义的路由助手。 How can I define (like regular method) own route helper which will be used like "model_name_path, model_name_url etc"?我如何定义(像常规方法一样)自己的路由助手,它将像“model_name_path、model_name_url 等”一样使用?

This solution worked for me.这个解决方案对我有用。

Add this code to the end of config/routes.rb file.将此代码添加到config/routes.rb文件的末尾。 Make sure to replace MyApp with your application's name.确保将MyApp替换为您的应用程序名称。

MyApp::Application.routes.named_routes.module.module_eval do
  def model_name_path(*args)
    # Your code here
  end

  def model_name_url(*args)
    # Your code here
  end
end

MyApp::Application.routes.named_routes.instance_eval do
  @helpers += [:model_name_path, :model_name_url]
end

These custom methods will be available in controllers, views and tests.这些自定义方法将在控制器、视图和测试中可用。

I know one possible answer for _path, but the same isn't working for me for _url.我知道 _path 的一个可能答案,但对于 _url 来说,这对我不起作用。 Anybody know why?有人知道为什么吗?

# at the bottom of config/routes.rb
module ActionView::Helpers::UrlHelper
    def model_name_path model, args={}
        # your implementation
    end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM