Add default params to named route helper in rails

Viewed 220

I have this route

get "/articles/:id" => "articles#show", as: :article

Which generates the path helper article_path(article).

Is it possible to add some default parameters to this path helper, like /articles/123?token=123456? For example I use the article_path helper a dozens of times and it would be tedious to always do something like

<%= article_path(article, token: article.token) %>

I've played around with the defaults of a route, but this does not affect the URL generation, only the params object when I'm on this route

get "/articles/:id" => "articles#show", as: :article, defaults: { token: "my token" }

The only thing I can think of, is to overwrite / monkey patch the helper, but as I need this logic on other helpers too, I was wondering if there is a build in way to do this.

1 Answers

This logic does not really belong in the routing layer and query string parameters are for the most part completely transparent to the router.

Instead you can just create your own helper method:

def article_path(article_or_id, **opts)
  if opts[:token].nil? && article_or_id.respond_to?(:token)
    super(article_or_id, opts.merge(token: article.token))
  else
    super
  end
end
Related