How can I globally override a rails url helper?

前端 未结 4 2180
时光取名叫无心
时光取名叫无心 2020-12-06 12:30

I needed to add a simple change to foo_path, so I did this:

module ApplicationHelper
  # [...]

  def foo_path(foo, options = {})
    option         


        
4条回答
  •  独厮守ぢ
    2020-12-06 13:12

    As the current answers show, you are not overriding a rails helper (as defined somewhere in the app/helpers folder) but a route helper (as defined in config/routes.rb).

    Calling the method foo_path from a view works, because first Rails will look through all available application helper methods before looking through the available routing helper methods.

    Calling the method from a controller does not work, because Rails will only go through the available routing helper methods, not through the routing helpers.

    If you want to call an application helper from a controller, use this inside your controller:

    view_context.foo_path(...)
    

    This requires you to prepend view_context. for every call to foo_path inside every controller, so it is not a perfect solution but it should work.

提交回复
热议问题