Thanks. That makes sense. Much appreciated! On Jan 3, 7:46 am, Rick DeNatale <rick.denat...@gmail.com> wrote: > On Sun, Jan 3, 2010 at 4:27 AM, acreadinglist <andrew.c...@gmail.com> wrote: > > 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)? > > 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 > > foo1 = Foo.new > foo1.m > foo2 = Foo.new > foo2.n > foo3 = Foo.new > > 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. > > -- > Rick DeNatale > > Blog:http://talklikeaduck.denhaven2.com/ > Twitter:http://twitter.com/RickDeNatale > WWR:http://www.workingwithrails.com/person/9021-rick-denatale > LinkedIn:http://www.linkedin.com/in/rickdenatale
-- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-t...@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.