Using routes in active record

August 07, 2019

Some times in rails you need to render the path in the model. Unfortunately calling user_path(self), will not out of the box in the model.

To accomplish this behavior, all you need to do is add the following to your model:

include Rails.application.routes.url_helpers

It is that simple. Now you can create methods that provide the url at a route.

def users_url
  user_path(self)
end

This should not be abused, and should be used sparingly. I used this to provide a url to algolia for our admin.


Search