Skip to content

Instantly share code, notes, and snippets.

@bruno-
Last active August 29, 2015 14:08
Show Gist options
  • Save bruno-/5964403476c791331c49 to your computer and use it in GitHub Desktop.
Save bruno-/5964403476c791331c49 to your computer and use it in GitHub Desktop.
Arel Examples
#--------------
# Basic Example
#--------------
require "./models"
name_variable = "Bill Smith"
# ActiveRecord
puts Customer.where(name: name_variable)
# Arel
puts Customer.where(Customer[:name].eq name_variable)
#--------------------------
# A bit more useful example
#--------------------------
require "./models"
sales_var = 999
# ActiveRecord
# NOT GOOD (will raise)
# puts Customer.joins(:sales).where(price: sales_var)
# GOOD
puts Customer.joins(:sales).where("sales.price" => sales_var)
# Arel
puts Customer.joins(:sales).where(Sale[:price].eq sales_var)
#------------------------
# SQL comparisons example
#------------------------
require "./models"
credits_var = 300
# ActiveRecord
puts Customer.where("credits > ?", credits_var)
# Arel
puts Customer.where(Customer[:credits].gt(credits_var))
# Comparison operators: gt, lt, gteq, lteq
#----------------------
# OR conditions example
#----------------------
require "./models"
var1 = 800
var2 = 300
# ActiveRecord
puts Customer.where("credits > ? OR credits < ?", var1, var2)
# Arel
puts Customer.where(
Customer[:credits].gt(var1).or(
Customer[:credits].lt(var2)
)
)
#---------------------------
# Complex conditions example
#---------------------------
require "./models"
var1 = 800
var2 = "Mary Smith"
var3 = 500
# ActiveRecord
puts Customer.where("credits > ? OR (name = ? AND credits < ?)", var1, var2, var3)
# Arel
puts Customer.where(
Customer[:credits].gt(var1).or(
Customer[:name].eq(var2).and(
Customer[:credits].lt(var3)
)
)
)
#-------------
# LIKE example
#-------------
require "./models"
name_var = "Mary"
# ActiveRecord
puts Customer.where("name LIKE ?", "%#{name_var}%")
# Arel
puts Customer.where(Customer[:name].matches("%#{name_var}%"))
require "active_record"
require "pg"
# AR connection
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
database: "lynda_test",
username: "bruno",
password: nil,
host: "localhost",
port: "5432",
)
# Columns:
# id :integer, primary_key
# name :string
# credits :integer
class Customer < ActiveRecord::Base
has_many :sales
def self.[](column)
arel_table[column]
end
def to_s
"id: #{id}, name: #{name}, credits: #{credits}"
end
end
# Columns:
# id :integer, primary_key
# customer_id :integer
# price :integer
class Sale < ActiveRecord::Base
belongs_to :customer
def self.[](column)
arel_table[column]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment