ActiveRecord::Base.exists? incompatibility with :include scopes fixed

23 views
Skip to first unread message

Peter Marklund

unread,
Apr 22, 2009, 7:38:17 AM4/22/09
to Ruby on Rails: Core
Hi!
I was using a default scope with an :order option as well as
an :include option and came across a bug in the
ActiveRecord::Base.exists? method. It turns out it drops any :include
option from the current scope. My solution is a bit radical maybe, but
simple. I have exists? invoke find_initial so that all the good code
in the find family of methods can be reused. See:

https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2543-make-activerecordbaseexists-invoke-find_initial-to-support-include-scopes#ticket-2543-2

Comments?

Thanks!

Peter
http://marklunds.com

Michael Koziarski

unread,
Apr 22, 2009, 10:24:20 PM4/22/09
to rubyonra...@googlegroups.com
> https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2543-make-activerecordbaseexists-invoke-find_initial-to-support-include-scopes#ticket-2543-2
>
> Comments?


Exists is only really for indicating whether or not there's a record
associated with that ID, if you want to obey all those other rules you
can just use .first(...) right? I'm -1 on this as it stands as exists
is really only there for this high-performance use case e.g. rarely

What's the use case you have in mind?

--
Cheers

Koz

Peter Marklund

unread,
Apr 23, 2009, 3:55:13 AM4/23/09
to Ruby on Rails: Core
> Exists is only really for indicating whether or not there's a record
> associated with that ID, if you want to obey all those other rules you
> can just use .first(...) right?  I'm -1 on this as it stands as exists

I'm not sure what you mean by "all those other rules". The exists?
method does take scope into account, but only partially - it
ignores :include - and so it bombs in certain scenarios (see my test
case). This bug needs to be fixed. If my fix is not appropriate, then
I would really appreciate if you could explain why, and even better if
you could propose an alternative approach.

> is really only there for this high-performance use case e.g. rarely

Well, I'm not sure it is relevant to discuss how often the method is
used here. The method is a public part of the API and has been for a
long time AFAIK and it needs to work. Correct functionality trumps
performance. Note that exists? is invoked by include? in
association_collection.rb. That's how the bug was triggered for me.

Do you think there is a significant performance impact of my change
and if so why?

Thanks for taking the time to discuss this!

Cheers

Peter
Reply all
Reply to author
Forward
0 new messages