I am working on a simple rails project and i would like to know if it is possible for me to find an object with two different parameters like
def show
@user = User.find_by_name(params[:name])
or
@user = User.find_by_id(params[:id])
end
In this case i want to be able to find users either by their id or by their name so that when i type the url like localhost:3000/users/mike it takes me to the users showpage of when i type
localhost:3000/users/4 it also takes me to the same users show page. Please how can this done if it is possible in rails.
I would probably define a special find method in your User model that could look something like this:
Then you could use this method in your controller like this:
Edit:
In addition, for this to be failsafe, you should probably make sure that a user name can not consist of only numbers so that it does not use
findby the id parameter when it has really been given a user name. But that can be handled by validations.