Using query objects to extract (complex) queries from models
Active Record provides an extensive API for querying database data. Without writing a pinch of SQL, you can achieve most of your data reading goals using the fluent API (a smart term for method chaining). In simple scenarios, the code is very easy to comprehend as it is read in plain English. Here is how we can load published posts ordered by their creation date (from newest to oldest):
Post.where(draft: false).order(created_at: :desc)#=> SELECT * FROM posts WHERE draft = 'f' ORDER BY created_at DESC
In recent versions of Rails, even complex queries can be constructed solely with Active Record methods. Let’s consider an example—loading a list of users whose posts published in the previous week have been bookmarked at least once:
User.with( bookmarked_posts: Post. .where(created_at: Date.current.prev_week.all_week) &...