Last active
August 14, 2017 03:11
-
-
Save stevepentler/08635a028b91b2c91500 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#unscoped | |
Class Item < ActiveRecord::Base | |
default_scope { where(status: "active") } | |
Item.all - returns only items with an active status | |
Item.unscoped.all - returns all items, regardless of whether they pass the validation | |
#Find using primary key | |
#can take an array as an arg to return client.id=1 and client.id=10 | |
client = Client.find([1, 10]) | |
#Take | |
client = Client.take(2) | |
#returns n amount of arguments | |
#optional arg | |
#First / #Last | |
client = Client.first(3) | |
#ordered by primary key | |
#optional arg | |
#Find_by | |
Client.find_by(first_name: "Esteban") | |
#Safe | |
Client.where("orders_count = ?", params[:orders]) | |
#Vulnerable to SQL Injectoin | |
Client.where("orders_count = #{params[:orders]}") | |
#multiple arguments, declare then pass in hash | |
#hash values can not be symbols | |
Client.where("created_at >= :start_date AND created_at <= :end_date", | |
{start_date: params[:start_date], end_date: params[:end_date]}) | |
#range | |
Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight) | |
#not | |
Article.where.not(author: author) | |
#order | |
Client.order(:created_at) | |
#descending | |
Client.order(created_at: :desc) | |
#multiple fields | |
Client.order(orders_count: :asc, created_at: :desc) | |
#distinct | |
Client.select(:name).distinct | |
#single record per unique value of a certain field | |
#offset | |
Client.limit(5).offset(30) | |
#skips over first 30 and returns max of 5 clients | |
#group return | |
Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)") | |
#Having | |
#specifies withing group | |
Order.select("date(created_at) as ordered_date, sum(price) as total_price"). | |
group("date(created_at)").having("sum(price) > ?", 100) | |
#returns orders > $100 | |
#unscope | |
#removes conditions and model validations | |
Article.where('id > 10').limit(20).order('id asc').unscope(:order) | |
#would return all orders and ignore the ascending id condition | |
#only | |
#overrides conditions | |
Article.where('id > 10').limit(20).order('id desc').only(:order, :where) | |
#ignores the limit condition and only accepts where conditions | |
#reorder | |
#overrides the default scope from the model | |
class Article < ActiveRecord::Base | |
has_many :comments, -> { order('posted_at DESC') } | |
end | |
Article.find(10).comments.reorder('name') | |
#orders by name instead of the posted at | |
#reverse_order | |
Client.where("orders_count > 10").order(:name).reverse_order | |
Orders by name in descending order | |
#accepts no arguments | |
#Joining single table | |
Category.joins(:articles) | |
#returns a category object for all categories with articles | |
add on unique if you want single list | |
#Joining multiple associations | |
Article.joins(:category, :comments) | |
#returns all articles that have a category and at least one comment | |
#Joining nested associations (single level) | |
Article.joins(comments: :guest) | |
#Return all articles that have a comment made by a guest | |
#Joining nested association (multiple levels) | |
Category.joins(articles: [{ comments: :guest }, :tags]) | |
#N + 1 problem | |
clients = Client.limit(10) | |
clients.each do |client| | |
puts client.address.postcode | |
end | |
#Makes 11 total queries to the database | |
#Solution to N + 1 problem (eager loading) | |
#includes | |
clients = Client.includes(:address).limit(10) | |
cleints.each do |client| | |
puts client.address.postcode | |
end | |
#Makes 2 queries | |
#Eager loading with multiple associations | |
Article.includes(:category, :comments) | |
#loads all articles and the associated category and comments for each | |
#Scoping | |
class Article < ActiveRecord::Base | |
scope :published, -> {where(published: true)} | |
end | |
#define common methods, same as self.published class method | |
#Chainable | |
class Article < ActiveRecord::Base | |
scope :published, -> {where(published: true)} | |
scope :published_and_commented, -> {published.where("commenents_count > 0")} | |
end | |
#unscoped | |
removes all scopes and default scopes | |
For every field (also known as an attribute) you define in your table, | |
Active Record provides a finder method. If you have a field called | |
first_name on your Client model for example, you get | |
find_by_first_name for free from Active Record. | |
#find_or_create_by | |
#Returns record that already exists or creates a new one | |
#find_or_initialize_by | |
#Returns record that already exists or new | |
#not saved into database | |
#pluck | |
Client.pluck(:id) | |
#returns all value in a column | |
Client.pluck(:id, :name) | |
#returns arrays of [:id, :name] | |
Client.pluck(:name).limit(1) | |
#exists | |
Client.exists?(1) | |
#returns true / false | |
#takes multiple values | |
Client.exists?(id: [1,2,3]) | |
Client.exists?(name: ['John', 'Sergi']) | |
#calculations | |
#.count | |
#.average("order_total") | |
#.minimum("age") | |
#.maximum("age") | |
#.sum("order_total") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment