RE: Re: Querying calculated fields of ActiveRecord

Again, the two methods I suggested each have drawbacks. Loading each
object and checking the method (A):

Products.find_all.select { |p| p.price < 30 }

works great in terms of OO, but is very slow.

Writing custom SQL (B) improves performance, but convolutes
the whole OO
thing.

I’d recommend a pragmatic approach… Do the right OO-thing, that
might be very slow. If that shows up as a performance problem, and
your profiling shows that it indeed is this calculated field that causes
the bad performance, replace that specific problem with some finetuned
SQL.

I don’t think this is an inherent problem with Active Record. If you had
perfect technology, how would this problem be solved?

Best regards,
torben

torben.wolm wrote:

I don’t think this is an inherent problem with Active Record. If you had
perfect technology, how would this problem be solved?

I am NOT trying to start flames, but Hibernate provides a very natural
syntax for this, where you can define how properties should be queried -
raw SQL, with a forumla, with a Java method, etc. You can modify this
on a per (sub)class basis.

I know of no smooth way of doing this in ActiveRecord. Sure, you can
override find_by_[name], but what about
find_by_[name]and[somethingelse]? Or what about :conditions => {…}.
Both of those cases will drop to the standard find. So, overriding the
find method in AR is asking for trouble, at least if you have more than
one developer - someone’s bound to forget that it is overridden, and use
one of the standard finds…

Really, there are two issues here:

  1. Being able to override a find method, so that it will be called when
    Rails generates a find_by_, or replaces in to :conditions hash
  2. Being able to do this on a per subclass basis.

1 is not so difficult a patch, but 2 would involve a huge rewrite of how
AR handles subclasses. (Currently, the SQL is totally unaware of
subclasses - they only come alive once the row has already been
fetched).