ActiveRecord methods Flashcards

1
Q

What is ActiveRecord pattern?

A

Maps one domain class to one database table, and one instance of that class to each row of that database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to use another table and primary_key for a model?

A
class Cat < ApplicationRecord
  self.table_name = 'animals'
  self.primary_key = 'id'
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to set a default value for the field on model level?

A
class Cat < ApplicationRecord
  attribute :name, :string, default: 'Default'
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to return the first record of a model or create a new one if the first doesn’t exist?

A

Cat.first_or_initialize(name: ‘d’) # new

Cat.first_or_create(name: ‘a’) # create

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to find records by an array of ids?

A

Cat.find([1,2])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to rewrite the field method in the model? ( name for example)

A

def name
read_attribute(:name) + “!!!”
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to return a record attributes like a hash?

A
Cat.last.attributes
# {"id"=>3, "name"=>"dd", "created_at"=>Sat, 25 Apr 2020 08:49:23 UTC +00:00, "updated_at"=>Sat, 25 Apr 2020 08:51:13 UTC +00:00}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does The Query cache work?

A

When the query cache is active, the corresponding result set is stored in a hash with the SQL that was used to query for them as the key. If the same SQL statement is used again in another operation, the cached result set is used to generate a new set of model objects instead of hitting the database again.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to turn on cache manually?

A
Cat.cache do
  puts Cat.first
  puts Cat.first
  puts Cat.first
end

will run only the first request, others will be cached

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to decrement, increment, or toggle the field?

A

Cat.last.increment!(:age)
Cat.last.decrement!(:age)
Cat.last.toggle!(:alive)

and the same without !

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to update a record and set updated_at with current time?

A

Cat.last.touch

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to show SQL query which rails method triggers?

A

Cat.where(id: 2).explain
# or
Cat.where(id: 2).to_sql

How well did you know this?
1
Not at all
2
3
4
5
Perfectly