Tim O
Tim O

Reputation: 731

Why does ActiveRecord have this idiosyncrasy?

The following query raises an exception:

User.find(4)

Whereas the following query returns nil:

User.find(:first, :conditions => "id = 4")

Do database wrappers ordinarily return 'nil' or 'null' etc when a record isn't found or do they raise exceptions? Is there something special about the addition of the 'first' keyword? Is this expected behavior or rails magic fizzling?

Upvotes: 2

Views: 67

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107728

Think about it like this:

In the first example, you're telling Active Record to find the record in the users table with the ID of 4, and it must exist.

In the second example, you're going to the long way and telling it "please search for records that have the id attribute equal to 4 and if there's any, return the first one". This is why it won't return anything.

The shorter way to do this would be to use find_by_id.

Upvotes: 3

Related Questions