Skip to content

Instantly share code, notes, and snippets.

@LolWalid
Last active January 20, 2016 14:53
Show Gist options
  • Save LolWalid/6b4610d7050e5f73576f to your computer and use it in GitHub Desktop.
Save LolWalid/6b4610d7050e5f73576f to your computer and use it in GitHub Desktop.
Some tips using active record, check the documentation
# http://guides.rubyonrails.org/active_record_querying.html
class Article < ActiveRecord::Base
has_many :comments, -> { order('posted_at DESC') }
end
##### REORDER #####
Article.find(10).comments.reorder(:name)
##### REVERSE_ORDER #####
Article.all.order('name asc')
Article.all.order("name #{params[direction]}")
Article.all.order(:name).reverse_order
##### N + 1 queries #####
# Problem
clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
end
# Solution
clients = Client.includes(:address).limit(10)
clients.each do |client|
puts client.address.postcode
end
##### MULTI JOINS #####
Category.joins(articles: [{ comments: :guest }, :tags])
##### Some maths #####
Article.count
Article.count(:name)
Article.count(1)
Article.minimum(:likes)
Article.maximum(:likes)
Article.sum(:likes)
Article.average(:likes) # -> Not working
Article.all.average(:likes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment