activerecord - How to reduce number of queries in this case on Rails -
i need bunch of queries.
in case think query result many times,
not completed in 1 query.
how create search results can done 1 query ?
q = weatherlog.nearby(100, longitude, latitude) if start_time , end_time @weather_logs = q.where(datetime: start_time..end_time) elsif start_time @weather_logs = q.where("datetime > ?", start_time) elsif end_time @weather_logs = q.where("datetime < ?", end_time) end @weather_logs = @weather_logs.order(datetime: :asc).first(2000)
the first thing realize activerecord not execute query until aboultely has (lazy loading). while there number of lines of code building query, query executed on methods .all
, .each
, .first
etc. performance standpoint code ok executing 1 query database , not many.
however can tweak code create more human readable , maintainable:
class weatherlog < activerecord::base # ... class << self def between_times(times) after_time(times[:start_time]).before_time(times[:end_time]) end def after_time(time) homecoming self.all if time.nil? where('datetime > ?', time) end def before_time(time) homecoming self.all if time.nil? where('datetime < ?', time) end end end
using self.all
skips query status while still enabling query chaining. makes possible remove of if/else logic. can chain queries (or create helper method within weatherlog
):
weatherlog.nearby(100, longitude, latitude).between_times(start_time: start_time, end_time: end_time)
ruby-on-rails activerecord ruby-on-rails-4
No comments:
Post a Comment