Missing Attribute: foo
Have you ever seen this confusing, difficult-to-solve error in Rails? missing attribute: foo for #<Bar:0xabcdef>
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 an attribute–either one from your model or an attribute you coded.
So what does it mean?
When you ask Rails for an attribute, it checks all the attributes specified in the database, and all the attributes you’ve added to your model code. And your attribute is there, in your model. Why can’t you see it? Chances are you forgot to include it in your select statement in a find_by_sql call!
For those who don’t know, instead of using ModelName.find, you can perform a lower-level find via SQL by calling the ModelName.find_by_sql function. It takes one parameter–an SQL statement to execute. It can be useful if you need to join tables or perform other complex searches that you can’t do with the built-in Rails framework.
But use it carefully! If your SQL contains vendor-specific code (such as MySQL’s LIMIT clause), your application loses it’s database-independence, and becomes tied down to your specific database.
So how do you fix this problem? Simply update your query to include your attribute of choice (or just make it a SELECT * if that makes it easier). You probably won’t stumble across this error unless you’re writing queries manually–but if it bites you, at least you’ll know how to solve it!
Tags: debugging, introductory Posted in


April 23rd, 2009 at 11:57 pm
Thanks so much. I found this answer in a few seconds of searching, and it was great to have a mystery error explained so quickly for a change.