Skip to content

Instantly share code, notes, and snippets.

@bradrobertson
Created August 19, 2011 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradrobertson/1155760 to your computer and use it in GitHub Desktop.
Save bradrobertson/1155760 to your computer and use it in GitHub Desktop.
Find by sql in ActiveRecord
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