0

The idea behind Friendly_ID is that you can use a slug or id to retrieve a record. So User.friendly.find(id) will retrieve a record using either the slug or id. If the record isn't found, it raises an error. I want to find the record but return nil if the record is not found. For now, the only way I know of is something like this:

u = User.find_by_id() || User.find_by_slug()

This won't search through old slugs plus it's clunky. Is there a cleaner solution?

gitb
  • 1,090
  • 2
  • 12
  • 20

2 Answers2

0

Not optimal but you could try using raw sql in a where method call. Try:

u = User.where("id ='...' or slug ='...')

If you want to avoid raw sql you can use Arel:

users = Arel::Table.new(:users)
u = users.where(users[:id].eq(...).or(users[:slug].eq('...')))
jaydel
  • 14,389
  • 14
  • 62
  • 98
0

If you want to have nil as value when the record is not found, you may assign nil in the rescue block like below:

begin
  u = User.friendly.find(id)
rescue ActiveRecord::RecordNotFound
  u = nil
end

As of find documentation, it raises ActiveRecord::RecordNotFound if no record can be found.

But if you don't want to use exception handling, then you may have to use the clunky solution:

u = User.find_by "id = ? or slug = ?", <ID>, <SLUG>
Wasif Hossain
  • 3,900
  • 1
  • 18
  • 20