Created
March 15, 2012 22:02
-
-
Save avdi/2047272 to your computer and use it in GitHub Desktop.
Using ActiveRecord::Relation.where_values_hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Problem: I need to add some model's default scope to an ARel query | |
# I don't know if everyone else already knew this, or if there's a | |
# a cleaner way; but this has been working well for me: | |
class OtherModel < ActiveRecord::Base | |
# ... | |
default_scope where(:deleted_at => nil) | |
# ... | |
end | |
original_query = SomeModel.where(...) | |
new_query = original_query.where(OtherModel.table_name => OtherModel.scoped.where_values_hash) |
Author
avdi
commented
Mar 15, 2012
via email
Does that actually pick up the default scope?
On Thu, Mar 15, 2012 at 6:06 PM, Ben Hamill ***@***.*** wrote:
Also `.joins(OtherModel.table_name)`, right?
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2047272
##
Avdi Grimm
http://avdi.org
I only check email twice a day. to reach me sooner, go to
http://awayfind.com/avdi
Oh. I don't think so. I'd meant that in order to have a where()
call refer to another table, you have to joins()
it in, right? Or belongs_to
and it's cousins in the relevant models?
Every time I have used default_scope
I've ended up regretting it.
I thought consensus was not to use it.
In my experience it's always more hassle to work around default_scope's subtle implications than to just use an explicit scope in the places where you access the Model.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment