Reputation: 48438
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
Upvotes: 2
Views: 961
Reputation: 32748
Implement a to_param
method 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
user_path(some_user)
generates a URL like /users/45
But lets say you have a unique username that you want to use in the route, so you would just do:
class User
def to_param
username
end
end
Then a call to user_path(user)
would generate something like: /users/blackbear
Upvotes: 4