Retrieving a Single Object
client = Client.find(10)
client = Client.take
client = Client.first
client = Client.last
Client.find_by first_name: ‘Lifo’
Client.where(first_name: ‘Lifo’).take
Client.find_by! first_name: ‘Lifo’
Retrieving Multiple Objects
client = Client.find([1, 10])
Client.take(2)
Client.first(2)
Client.last(2)
Retrieving Multiple Objects in Batches
User.all.each do |user|
NewsLetter.weekly_deliver(user)
end
Conditions
Pure String Conditions
Client.where(“orders_count = ‘2’”)
Client.where(“orders_count = ?”, params[:orders])
Client.where(“orders_count = ?”, params[:orders])
Client.where(“orders_count = #{params[:orders]}”)
Client.where(orders_count: [1,3,5])
Post.where.not(author: author)
Ordering
Client.order(:created_at)
# OR
Client.order(“created_at”)
Selecting Specific Fields
Client.select(:name).distinct
Limit and Offset
Client.limit(5)
Client.limit(5).offset(30)
Group
Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).group(“date(created_at)”)
Having
Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).
group(“date(created_at)”).having(“sum(price) > ?”, 100)
Overriding Conditions
Post.where(‘id > 10’).limit(20).order(‘id asc’).except(:order)
Post.where(‘id > 10’).limit(20).order(‘id desc’).only(:order, :where)
Client.where(“orders_count > 10”).order(:name).reverse_order
Null Relation
Post.none
Readonly Objects
client = Client.readonly.first
client.visits += 1
client.save
Optimistic Locking
c1 = Client.find(1)
c2 = Client.find(1)
c1.first_name = “Michael”
c1.save
c2.name = “should fail”
c2.save # Raises an ActiveRecord::StaleObjectError
Find or Build a New Object
find_or_create_by
Client.find_or_create_by(first_name: ‘Andy’)
find_or_initialize_by
The find_or_initialize_by method will work just like find_or_create_by but it will call new instead of create. This means that a new model instance will be created in memory but won’t be saved to the database. Continuing with the find_or_create_by example, we now want the client named ‘Nick’:
Finding by SQL
Client.find_by_sql(“SELECT * FROM clients
INNER JOIN orders ON clients.id = orders.client_id
ORDER BY clients.created_at desc”)
Existence of Objects
Client.exists?(1)
Calculations
Client.coun
Client.where(first_name: ‘Ryan’).count
Client.includes(“orders”).where(first_name: ‘Ryan’, orders: { status: ‘received’ }).count
Client.average(“orders_count”)
Client.minimum(“age”)
Client.maximum(“age”)
Client.sum(“orders_count”)
Form Helpers
<%= form_tag do %>
A Generic Search Form
<%= form_tag(“/search”, method: “get”) do %>
<%= label_tag(:q, “Search for:”) %>
<%= text_field_tag(:q) %>
<%= submit_tag(“Search”) %>
<% end %>
Checkboxes
<%= check_box_tag(:pet_dog) %>
<%= label_tag(:pet_dog, “I own a dog”) %>
<%= check_box_tag(:pet_cat) %>
<%= label_tag(:pet_cat, “I own a cat”) %>
Radio Buttons
<%= radio_button_tag(:age, “child”) %>
<%= label_tag(:age_child, “I am younger than 21”) %>
<%= radio_button_tag(:age, “adult”) %>
<%= label_tag(:age_adult, “I’m over 21”) %>
Helpers
<%= text_area_tag(:message, “Hi, nice site”, size: “24×6”) %>
<%= password_field_tag(:password) %>
<%= hidden_field_tag(:parent_id, “5”) %>
<%= search_field(:user, :name) %>
<%= telephone_field(:user, :phone) %>
<%= date_field(:user, :born_on) %>
<%= datetime_field(:user, :meeting_time) %>
<%= datetime_local_field(:user, :graduation_day) %>
<%= month_field(:user, :birthday_month) %>
<%= week_field(:user, :birthday_week) %>
<%= url_field(:user, :homepage) %>
<%= email_field(:user, :address) %>
<%= color_field(:user, :favorite_color) %>
<%= time_field(:task, :started_at) %>
<%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %>
<%= range_field(:product, :discount, in: 1..100) %>
The Select and Option Tags
<%= select_tag(:city_id, ‘<option value=”1″>Lisbon</option>…’) %>
TIme zone
<%= time_zone_select(:person, :time_zone) %>
Country select
https://github.com/stefanpenner/country_select
Using Date and Time Form
<%= select_date Date.today, prefix: :start_date %>
<%= select_year(2009) %>
<%= select_year(Time.now) %>
Uploading Files
<%= f.file_field :picture %>
layout helpers
<%= javascript_include_tag “main”, “columns” %>
<%= stylesheet_link_tag “http://example.com/main.css” %>
<%= image_tag “header.png” %>
<%= video_tag “movie.ogg” %>
<%= audio_tag “music.mp3” %>