Skip to content

Instantly share code, notes, and snippets.

@mskyle
Created October 24, 2013 18:36
Show Gist options
  • Save mskyle/7142611 to your computer and use it in GitHub Desktop.
Save mskyle/7142611 to your computer and use it in GitHub Desktop.
def self.filter(filter_hash, user = nil, sort_column = "height", sort_direction = "desc")
query_start = "SELECT * FROM mountains "
query = query_start
if filter_hash.has_key?(:hiked)
hike_query = "INNER JOIN trip_mountains ON mountains.id = trip_mountains.mountain_id " +
"INNER JOIN trips ON trip_mountains.trip_id = trips.id " +
"INNER JOIN trip_participations ON trips.id = trip_participations.trip_id " +
"WHERE trip_participations.user_id = #{user.id} "
if filter_hash[:hiked] == :hiked
query += hike_query
elsif filter_hash[:hiked] == :unhiked
query += " EXCEPT SELECT * FROM mountains " + hike_query
end
if filter_hash.has_key?(:list)
query += " INTERSECT " + query_start
end
end
if filter_hash.has_key?(:list)
list_query = "INNER JOIN mountain_lists ON mountains.id = mountain_lists.mountain_id WHERE mountain_lists.list_id = #{filter_hash[:list]}"
query += list_query
end
if filter_hash.has_key?(:height)
height_query = "height < #{filter_hash[:height][:top]} AND height > #{filter_hash[:height][:floor]}"
if query.include?("WHERE")
query += " AND " + height_query
else
query += " WHERE " + height_query
end
end
query += " ORDER BY #{sort_column} #{sort_direction}"
Mountain.find_by_sql(query)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment