Created
August 19, 2011 01:10
-
-
Save bradrobertson/1155760 to your computer and use it in GitHub Desktop.
Find by sql in ActiveRecord
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
def self.open_for_participant(contact_id, group_id = nil) | |
find_by_sql(<<-SQL) | |
SELECT challenges.* FROM challenges | |
LEFT OUTER JOIN challenge_participants ON challenge_participants.challenge_id = challenges.id | |
AND challenge_participants.contact_id = #{contact_id} | |
WHERE (EXISTS ( | |
SELECT 1 FROM group_challenges | |
JOIN group_contacts ON group_challenges.group_id = group_contacts.group_id | |
#{"JOIN groups on group_challenges.group_id = groups.id" if group_id} | |
WHERE group_contacts.contact_id = #{contact_id} | |
AND group_challenges.challenge_id = challenges.id | |
AND group_challenges.restrict_participants = TRUE | |
#{"AND groups.id = #{group_id}" if group_id} | |
) | |
#{"OR open_to_all = TRUE" unless group_id}) | |
AND challenge_participants.id is NULL | |
AND (challenges.due_date IS NULL OR challenges.due_date >= '#{Time.now}') | |
AND challenges.state = 'active' | |
AND challenges.published = TRUE | |
SQL | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment