ActiveRecord Features Flashcards

1
Q

How to add a scope?

A

scope :scope_sample, -> { where(name: ‘d’) }

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

How to add a scope inside another scope?

A

scope :scope_sample, -> { where(name: ‘d’) }

scope :another_scope, -> { scope_sample.where(email: ‘a’) }

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

How to add a scope with params?

A

scope :scope_sample, ->(name) { where(name: name) }

User.scope_sample(‘a’)

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

How to add a default scope?

A

default_scope { where(name: ‘d’) }

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

How to remove default scope?

A

User.unscoped

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

What the main callback do you know? ( 4 )

A
before_destroy :sample
  before_create :sample
  after_create :sample
  before_save :sample
  after_save :sample
  before_validation :sample
  after_validation :sample

def sample
p “Hello”
end

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

How to add attribute options and convert types on a model level?

A

attribute :name, :integer, default: 10

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

Why do we need serialize in a model?

A

It allows us to store value in text format in the database and then to transform to whatever you need. ( To hash for example )

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

How to use serialization?

A

serialize :description, Hash

# User.create(description: {a: 1 })
# creates "description", "---\n:a: 1\n"
# User.last.description
# => {:a=>1}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is active_record store?

A

It’s the same as serialization

serialize :description, Hash
# or
store :description

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

What is enum?

A

Allows you to set a restriction for field values ( from speciific array)

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

How to add enum?

A

enum status: [:my_invalid, :my_valid]

add integer field to the db ( because it’s store only index)

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

How to set index explicitly to enum field?

A

enum status: { my_invalid: 0, my_valid: 1 }

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

How to use enum helpers? ( 3 ways )

A
class User < ApplicationRecord
  enum status: [:my_invalid, :my_valid]
end
  1. check current status
# user.my_invalid? 
# user.my_valid?
  1. update status
# user.my_invalid! 
# user.my_valid!
  1. return scope
# User.my_invalid 
# returns all record with this status
How well did you know this?
1
Not at all
2
3
4
5
Perfectly