Created
February 11, 2013 03:05
-
-
Save agraves/4752183 to your computer and use it in GitHub Desktop.
UserSearch refactor
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
class UserSearch | |
def self.search(term, topic_id = nil) | |
scope = User.scoped | |
if topic_id | |
scope = scope.joins(" | |
LEFT JOIN ( | |
SELECT DISTINCT(posts.user_id) | |
FROM posts | |
WHERE topic_id = #{topic_id.to_i} | |
) s ON s.user_id = users.id | |
") | |
scope = scope.order('s.user_id IS NULL') | |
end | |
scope = scope.order(' | |
last_seen_at IS NULL ASC, | |
last_seen_at DESC, | |
username ASC | |
') | |
scope = scope.where(" | |
username_lower LIKE :term_like OR | |
TO_TSVECTOR('simple', name) @@ | |
TO_TSQUERY('simple', | |
REGEXP_REPLACE( | |
REGEXP_REPLACE( | |
CAST(PLAINTO_TSQUERY(:term) AS text) | |
,'\''(?: |$)', ':*''', 'g'), | |
'''', '', 'g') | |
)", term: term, term_like: "#{term.downcase}%") | |
scope.limit(20) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Agree
Disagree
.joins(...)
should behave more like.where(...)
.http://guides.rubyonrails.org/active_record_querying.html
And, no, stating that it's "just a reinvention of the ActiveRecord wheel" is emphatically not a statement of taste, whatever you think about it. Every single method you've implemented has a corresponding method in ActiveRecord with the SAME NAME that does the SAME THING. Your library is a strict subset of the built-in ORM that lacks the flexibility and community testing that ActiveRecord has received over the years.
Don't get me wrong, AR is not perfect. It can be improved and it has shortcomings. However, I see absolutely nothing in your library that indicates you hit a wall with AR or saw some huge shortcoming.
PS Just to be clear, I think it's great that you're open-sourcing this project and using Rails. I strongly prefer to be direct in the interest of time.