SQL Flashcards
Retrieving a Single Object
Client.find this is the same as
SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
what is the difference between Client.take and Client.find
client = Client.take The take method retrieves a record without any implicit ordering.
SELECT * FROM clients LIMIT 1
what does Client.first return? what would Client.first(3) return?
The first method finds the first record ordered by primary key (default)
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
the value passed in returns that number of results
Client.find_by first_name: ‘Lifo’
is the same as:
Client.where(first_name: ‘Lifo’).take and in SQL
SELECT * FROM clients WHERE (clients.first_name = ‘Lifo’) LIMIT 1
Client.where(“orders_count = ?”, params[:orders]) why the question mark?
Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.where(“first_name LIKE ‘%#{params[:first_name]}%’”) is not safe.
Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).group(“date(created_at)”)
And this will give you a single Order object for each date where there are orders in the database.
how to do joins in active record?
You can just supply the raw SQL specifying the JOIN clause to joins:
Author.joins(“INNER JOIN posts ON posts.author_id = authors.id AND posts.published = ‘t’”)
hw to join multiple records?
Article.joins(:category, :comments) which is:
SELECT articles.* FROM articles
INNER JOIN categories ON categories.id = articles.category_id
INNER JOIN comments ON comments.article_id = articles.id
when do we join?
A simple joins statement lets you return records that have an associated record.
for example Category.joins(:products)
This query returns all categories that have products. It will return a category for every match it finds, which means there can be many duplicates. https://www.learneroo.com/modules/137/nodes/768