Is there a way to override rails route helper methods so that they handle model instances differently? I just finished creating a User model that does not inherit from ActiveRecord::Base, but instead uses methods that I wrote to retrieve users from an LDAP database. However, now all the route helper methods are messed up. (For example, user_path(user) gives /users/#<User:0x3df82a0> instead of /users/002131)
I tried overriding the method with the following code (placed inside of the User model) but it doesn’t seem to be doing anything. Any ideas?
class << Rails.application.routes.url_helpers
def user_path(user)
if user.class == User
users_path + "/#{user.id}"
else
users_path + "/#{user}"
end
end
end
Implement a
to_parammethod on your model and when you pass that to a route helper it should call that method.An example: most of the time you route by a Model ID, so a call like
generates a URL like
/users/45But lets say you have a unique username that you want to use in the route, so you would just do:
Then a call to
user_path(user)would generate something like:/users/blackbear