1

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.

2
  • 1
    I can't tell from the code you posted, but you might want to look at what the failing attribute.to_sym is. Also, you probably know this already, but Foo.find(:all)[0] is horribly inefficient- use Foo.first instead. Commented Apr 21, 2010 at 23:33
  • attribute.to_sym converts an attribute name that is a String (eg, 'author' to a symbol ':author'. Symbols are the data-type accepted by the Object#method function. This works in principle as only some of the methods are undefined. Also, I know the db query is terrible, it's not what I'm actually using, it's just easier for everyone else to understand. Commented Apr 21, 2010 at 23:40

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Don't worry about the query, it's not returning a nil result. And thanks for the .to_sym tip.
0

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?

1 Comment

All of the attributes that tripped the error were database columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.