开发者

Ruby: Dynamically calling available methods raising undefined method (metaprogramming)

I have an Activerecord object called Foo:

Foo.attribute_names.each do |attribute|
  puts Foo.find(:all)[0].method(a开发者_如何学Cttribute.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.


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)


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜