Querying Rails models
Most methods can be chained.
By primary key
Find by id. Raises an exception if none were found.
post = Post.find(123)
Filtering
where
is the main method of filtering
Post.where(published: true)
Custom conditions
Post.where("likes > 100")
Binds
Post.where("created_at >= :start_date", {start_date: params[:start_date])
Limiting output
Post.where("likes > 100").limit(10)
Offsetting — limit
+ offset
is useful for pagination
Post.where("likes > 100").limit(10).offset(20)
Ordering
Default ordering is asc
, of course, but you can specify.
Post.order(created_at: :desc)