An Array returned by a model association is not an Array?
Posted
by
Warren
on Stack Overflow
See other posts from Stack Overflow
or by Warren
Published on 2011-03-11T22:03:43Z
Indexed on
2011/03/12
0:10 UTC
Read the original article
Hit count: 152
We have a model association that looks something like this:
class Example < ActiveRecord::Base
has_many :others, :order => 'others.rank'
end
The rank column is an integer type. The details of these particular models are not really important though as we have found the same problem with other has_many associations between other models.
We have also added to the Enumerable module:
module Enumerable
def method_missing(name)
super unless name.to_s[0..7] == 'collect_'
method = name.to_s[8..-1]
collect{|element| element.send(method)}
end
end
This adds a collect_id method that we can use to get an array of record ids from an array of ActiveRecord objects.
So if we use a normal ActiveRecord find :all, we get a nice array which we can then use collect_id on but if we use Example.others.collect_id, we get
NoMethodError: undefined method `collect_id' for #<Class:0x2aaaac0060a0>
Example.others.class returns "Array" so is it lying or confused?
Our solution thus far has been to use it this way:
Example.others.to_a.collect_id
This works but this seems a bit strange. Why would you have to do that?
We are on Ruby 1.8.7 and Rails 2.3.4
© Stack Overflow or respective owner