Created
July 29, 2012 09:48
-
-
Save alvir/3197130 to your computer and use it in GitHub Desktop.
Funny scopes
This file contains hidden or 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
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