How to override routes path helper in rails?

扶醉桌前 提交于 2020-01-12 09:02:25

问题


My route is defined like this

match '/user/:id' => 'user#show', :as => :user

If for some reason a nil ID is passed I want the route helper to return only '#' and if ID is not nil i want it to return normal path like '/user/123'. or is there any better way to do it. this route helper has been used in lot of places in my code so I dont want to change that. Instead I am looking for one place which will effect all instances of user_path.

Thanks


回答1:


module CustomUrlHelper
  def user_path(user, options = {})
    if user.nil?
      "#"
    else
      super
    end
  end
end

# Works at Rails 4.2.6, for older versions try http://stackoverflow.com/a/31957323/474597
Rails.application.routes.named_routes.url_helpers_module.send(:include, CustomUrlHelper)



回答2:


I did this in app/helpers/url_helper.rb

module UrlHelper
  def resource_path(resource, parameters = {})
    # my implementation
    "/#{resource.category}/#{resource.name}#{ "?#{parameters.to_query}" if parameters.present? }"
  end
end

I know there are ways to define such a nested route but I have a codebase using that route in several parts, as the question states.

I tried to alias old method, but was not recognised:

alias_method :old_resource_path, :resource_path


来源:https://stackoverflow.com/questions/15354355/how-to-override-routes-path-helper-in-rails

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