You need to index your data correctly, otherwise it will not work efficiently. If you use day granularity, then the presence of the Date column pays. Then you can use the standard SQL GROUP BY operation to get the values ββyou need.
For example, migration can be performed as follows:
self.up add_column :posts, :created_on_date add_index :posts, :created_on_date execute "UPDATE posts SET created_on_date=created_at" end
Then the search is very fast, since it can use the index:
def sparkline_data self.class.connection.select_values(" SELECT created_on_date, COUNT(id) FROM posts WHERE created_on_date>DATE_SUB(UTC_TIMESTAMP(), INTERVAL 14 DAY) GROUP BY created_on_date ").collect(&:to_i) end
Keep in mind, if you may be absent during the day, you will have to consider this by inserting a null value in your results. The date returns here, so you should be able to calculate the missing values ββand fill them out. This is usually accomplished by repeating for several days using a collection.
When you need to quickly get a thin piece of data, loading model instances will always be a huge bottleneck. Often you need to go directly to SQL if there is no easy way to get what you need.
source share