Returning an object that might be nil

So I have a question that I haven’t been able to find the answer to.

Let’s say I have an api method that :returns an ActiveRecord::Base
object. In that class (say, Cat < ActiveRecord::Base) I have a method
that finds a cat given by an id and returns that record in the database.


api_method :findcat
:expects => [{:catid}]
:returns => [Cat]
is the api call. The controller calls get_cat in Cat <
ActiveRecord::Base, which does self.find(cat_id).

Now, if there is no Cat with id cat_id, the result will be nil,
according to the documentation for ActiveRecord’s find.

Will things go boom if someone calls the api method with an non-existant
id? Or will it return a Cat object that just happens to be nil?

I’m thinking the latter but really aren’t sure.

Don’t over-engineer your models in Rails.

You already get what you’re looking for automatically.

Given this class (entire contents)

class Cat < ActiveRecord::Base

You can do the following:

@cat = Cat.find(1)
Will throw exception if you don’t pass in a valid id

@cat = Cat.find_by_id(1)
returns nil

There’s no need for your own special API. This is why ActiveRecord
exists -
to keep you from having to write these methods yourself. #find and its
variants are all public class methods. No need to wrap them :slight_smile:

Hope that helps.

On Nov 30, 2007 1:04 PM, Erin K. [email protected]

This is really an oversimplification of what I want, but I do that
because what I care about is retrieving an object. I find that for me
when I am learning a new language, the simplest examples are the best to
learn from.

Thanks for your answer.