2

So I want to be able to get an object using find_by_id_or_name, I feel like I saw another question like this but am trouble finding any resources on making my own finder.

JP Silvashy
  • 46,977
  • 48
  • 149
  • 227

1 Answers1

5

You can do this by adding a class method to your model e.g.

class Model < ActiveRecord::Base
  def self.find_by_id_or_name(id_or_name)
    find :first, :conditions => ['id = ? or name = ?', id_or_name, id_or_name]
  end

  def self.find_all_by_id_or_name(id_or_name)
    find :all, :conditions => ['id = ? or name = ?', id_or_name, id_or_name]
  end
end

You will then by able to do

Model.find_by_id_or_name(id_or_name)

You can customise the method slightly depending on your requirements e.g. if you want to try by id first and then by name you could use Model.exists? first to see if there is matching record before doing a find_by_name. You could also look if id_or_name consisted of characters 0-9 and assume that was an id and only search by name if it contained other characters.

mikej
  • 65,295
  • 17
  • 152
  • 131