views:

135

answers:

3

I have an Activerecord object called Foo:

Foo.attribute_names.each do |attribute|
  puts Foo.find(:all)[0].method(attribute.to_sym).call
end

Here I'm calling all attributes on this model (ie, querying for each column value). However, sometimes, I'll get an undefined method error.

How can ActiveRecord::Base#attribute_names return an attribute name that when converted into its own method call, raises an undefined method error?

Keep in mind this only happens on certain objects for only certain methods. I can't identify a pattern.

Thank you.

A: 

Maybe something to do with access? Like if a class has an attr_protected attribute, or something along that line. Or for attributes that are not database columns, which have no accessors defined?

JRL
All of the attributes that tripped the error were database columns.
+1  A: 

The NoMethodError should be telling you which method does not exist for what object. Is it possible that your find returns no record? In that case, [][0] is nil and you will get a NoMethodError for sure.

I would use .fetch(0) instead of [0], and you will get a KeyError if ever there is no element with index 0.

Note: no need for to_sym; all builtin methods accept name methods as strings or symbols (both in 1.8 and 1.9)

Marc-André Lafortune
Don't worry about the query, it's not returning a nil result. And thanks for the .to_sym tip.
A: 

user94154: Could you try and see if you still get

# assuming Foo is the model not the object

Foo.column_names.each do |attribute|
  puts Foo.find(:first).send attribute
end
daya