Skip to content

Instantly share code, notes, and snippets.

@andreaseriksson
Last active December 17, 2015 17:49
Show Gist options
  • Save andreaseriksson/5648267 to your computer and use it in GitHub Desktop.
Save andreaseriksson/5648267 to your computer and use it in GitHub Desktop.
RAILS Activerecord querys
#Querys
Foo.order("published_at desc").limit(10)
Foo.where("published_at <= ?", Time.now).includes(:comments)
Foo.order("published_at").last
#Group by
Foo.order("DATE(start_at)").group("DATE(start_at)").count
Team.where(name: 'Justice League').first_or_create!
#Rails 4
Member.pluck(:name, :bio) # >> [["Superman", "From Krypton"], ["Batman", "From Gotham City"]]
# Scopes
scope :recent, lambda{ |num = nil| order("DATE(exposed_at) DESC").limit(num) }
scope :type, lambda{|model| where(exposable_type: model)}
#n+1
@categories = Category.order(:name).includes(:products)
#Arel
t = Product.arel_table
t[:price].eq(2.99)
t[:name].matches('%lore')
t[:price].eq(2.99).or(t[:name].matches('%lore')
Product.where(t[:price].eq(2.99).or(t[:name].matches('%lore')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment