How to define own routing helpers in rails 3?

ε祈祈猫儿з 提交于 2019-12-06 02:09:38

问题


I use polimorphic_path and it some buggy. This method require some route helper that not defined. How i can define (like regular method) own route helper wich will be used like "model_name_path, model_name_url etc"?


回答1:


This solution worked for me.

Add this code to the end of config/routes.rb file. Make sure to replace MyApp with your application's name.

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.




回答2:


I know one possible answer for _path, but the same isn't working for me for _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


来源:https://stackoverflow.com/questions/6470656/how-to-define-own-routing-helpers-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!