Hi, how do I overwrite the size method that gets created by AR (or is it?). Example: I have a model with class Contentnode < ActiveRecord::Base has_many :children, :class_name => ''Contentnode'', :finder_sql => ''SELECT * FROM contentnodes WHERE id <> #{id} AND lft BETWEEN #{lft} AND #{rgt}'' ... end Now when in my code I do a node = Contentnode.find(1) # this is root node.children.size #-> 9 It seems that the size method is created by AR. It emit the following SQL SELECT * FROM contentnodes WHERE id = ''1'' SELECT COUNT(*) FROM contentnodes WHERE id <> 1 AND lft BETWEEN 1 AND 18 which is correct, but not what I want. I want to be able to overwrite the #size method so I can issue my own query or behaviour. How do I do that? -- Sascha Ebach
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Sascha Ebach wrote: | how do I overwrite the size method that gets created by AR (or is it?). Here is a patch which adds :counter_sql option for has_many. ~ http://dev.rubyonrails.org/trac.cgi/ticket/265 ~ class Contentnode < ActiveRecord::Base ~ has_many :children, :class_name => ''Contentnode'', ~ :finder_sql => ''SELECT * FROM contentnodes ...'' ~ :counter_sql => ''SELECT COUNT(*) FROM contentnodes ...'' ~ end Best, jeremy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.6 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBsAxvAQHALep9HFYRAiiVAKCgjIuGNK24Q2Atgz+FJ1lylA/BmwCgnDcF zUXFN5v1tT+pjBDmuSNyjn4=Ucgu -----END PGP SIGNATURE-----
Hi Jeremy, Jeremy Kemper wrote:> -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Sascha Ebach wrote: > | how do I overwrite the size method that gets created by AR (or is it?). > > Here is a patch which adds :counter_sql option for has_many. > ~ http://dev.rubyonrails.org/trac.cgi/ticket/265 > > ~ class Contentnode < ActiveRecord::Base > ~ has_many :children, :class_name => ''Contentnode'', > ~ :finder_sql => ''SELECT * FROM contentnodes ...'' > ~ :counter_sql => ''SELECT COUNT(*) FROM contentnodes ...'' > ~ endThank you for the patch. It will be useful for other cases. But, actually, in this case I don''t want to issue another sql statement. I better explain a little more. I use preorder tree traversal in my CMS. Very much like here: http://rforum.andreas-s.net/trac/file/rforum/app/models/post.rb The thing is. Since this mechanism provides a way to extract the size of a subtree without doing a query. You can read about that here: http://www.sitepoint.com/print/hierarchical-data-database (under Headline "How Many Descendants") children.size = (right – left - 1) / 2 So to get the number of children I can simply do a little math without the roundtrip to the database, which is what I was trying to avoid ;) I would like to have something like this def size # no sql query here since none is needed (self.rgt - self.lft - 1) / 2 end -- Sascha Ebach