Q:

Finding objects with two parameters

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.

A:

I would probably define a special find method in your  User model that could look something like this:
class User < ActiveRecord::Base

  def self.find_by_id_or_name(arg)
    # Checks to see if the supplied argument is numerical i.e. an id, not name
    if arg.match(/^[0-9]+$/)
      # send argument to default find method that looks up by id
      User.find(arg)
    else
      # send argument to find_by_name! to look up record by name instead.
      # The added ! makes sure that if no record is found, an RecordNotFound error is raised
      User.find_by_name!(arg)
    end
  end
end

Then you could use this method in your controller like this:
def show
  @user = User.find_by_id_or_name(params[:id])
end

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 find by the id parameter when it has really been given a user name. But that can be handled by validations.

