[Rails] How do I overwrite AR-created magic methods?
Sascha Ebach
se at digitale-wertschoepfung.de
Fri Dec 3 12:05:21 GMT 2004
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 ...'
> ~ end
Thank 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
More information about the Rails
mailing list