Can someone clarify what type of object is returned from a find
(:select => ...) statement that only selects a subset of the records
columns?
If I have an object Foo with attributes A and B, and call find(:select
=> "A"), is the object that's returned still a Foo object? Is it a
new Foo object? Does it not have a B attribute (which would mean
there would exist more than one type for Foo)? or is the B attribute
simply nil?
Is there a way to replicate the behavior of the :select on an object -
to return an object that appears to be the same type but has a subset
of the attributes?
Can someone clarify what type of object is returned from a find
(:select => ...) statement that only selects a subset of the records
columns?
Foo.find always returns instances of Foo. That instance may have extra
attributes, it may have fewer attributes or the attributes may have
values other than what they would have if you had just done Foo.find
(1). Not sure what you mean by multiple types of Foo
First of all, assuming that you mean class for type here, presumably
because you are coming from a language like Java or C++, Ruby doesn't
work the same way.
In Ruby different instances of the same class can have different sets
of instance variables. Instance variables aren't declared in the
class definition, an object acquires instance variables when they are
referenced in instance methods, and those instance methods can come
from modules as well as classes, so if we have
class Foo
def m
@iv1 = 1
end
def n
@iv2 = 2
end
end
At this point foo1 will have @iv1, but not @iv2, foo2 will have @iv2
but not iv1, and foo3 will have neither instance variable.
Second, in the case of ActiveRecord attributes, theses aren't direct
instance variables at all. Instead an instance ActiveRecord::Base or
one of its subclasses has an @attributes instance variable which
contains a hash from attribute names to attribute values. The accessor
methods for models are dynamically generated and will generate errors
as appropriate, for example lets say you have a model Foo with
attributes, first_name, and last_name, and do
f = Foo.first(:select => 'first_name')
f.last_name
will raise an error:
ActiveRecord::MissingAttributeError: missing attribute: last_name
This may seem strange to someone accustomed to statically typed
systems, but it actually works rather well in practice. It just might
take some getting used to.