Skip to content

Instantly share code, notes, and snippets.

@avdi
Created March 15, 2012 22:02
Show Gist options
  • Save avdi/2047272 to your computer and use it in GitHub Desktop.
Save avdi/2047272 to your computer and use it in GitHub Desktop.
Using ActiveRecord::Relation.where_values_hash
# 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)
@avdi
Copy link
Author

avdi commented Mar 15, 2012 via email

@benhamill
Copy link

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?

@alassek
Copy link

alassek commented Mar 15, 2012

Every time I have used default_scope I've ended up regretting it.

@janv
Copy link

janv commented Mar 16, 2012

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