Skip to content

Instantly share code, notes, and snippets.

@alvir
Created July 29, 2012 09:48
Show Gist options
  • Save alvir/3197130 to your computer and use it in GitHub Desktop.
Save alvir/3197130 to your computer and use it in GitHub Desktop.
Funny scopes
class Feed < ActiveRecord::Base
scope :searchable, where(some_conditions)
scope :matchable, lambda {
where("url in
(SELECT du.url from
(SELECT url, count(*) cc
FROM feeds
WHERE (#{Feed.searchable_conditions})
GROUP by url
HAVING cc=1) du) and #{Feed.searchable_conditions}")
# First Feed.searchable_conditions only for optimization
}
def self.searchable_conditions
searchable_sql_array = searchable.where_values
ActiveRecord::Base.send(:sanitize_sql_array, searchable_sql_array)
end
end
# After refactoring
class Feed < ActiveRecord::Base
scope :searchable, where(some_conditions)
scope :matchable, searchable.group("url").having("count(*)=1")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment