Undefined Method Foo

Have you ever seen this confusing, difficult-to-solve error in Rails? undefined method foo for #

The error points to a line where you play around with @some_bar.foo, where @some_bar is an instance of the class Bar. Foo is a non-database-driven variable/attribute you’ve added to your Bar class model.

So what does it mean?

When Rails tries to grab @some_bar.foo, it checks through the database-driven attributes for foo, the model attributes for foo, the model methods for foo, and finds nothing. And then it says “Hey, I didn’t find this, and it’s probably a method,” so it gives you an “undefined method” error.

Hey, wait a minute. Did it just check the attributes for @some_bar, and didn’t find anything? It did! But you added the attribute! What’s going on? You probably forgot to add the attribute-reader accessors for foo! And that’s why Rails can’t find it!

The solution is easy–simply pop into your Bar mode class file and add the read-write accessor, like so:

attr_accessor :foo

And voila, you’re done! You probably won’t stumble across this error, since all the models in Rails derive their attributes from the database. But it might help to know if you’re writing non-database-derived attributes in your models.

Incidentally, attr_accessor is not Rails-specific–it’s the Ruby way of making member variables publicly accessible, either for reading or writing. It’s equivalent to adding both attr_reader :foo (to make :foo readable), and attr_writer :foo (to make :foo writable).

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , , , . Bookmark the permalink.