ActiveRecord Features Flashcards
How to add a scope?
scope :scope_sample, -> { where(name: ‘d’) }
How to add a scope inside another scope?
scope :scope_sample, -> { where(name: ‘d’) }
scope :another_scope, -> { scope_sample.where(email: ‘a’) }
How to add a scope with params?
scope :scope_sample, ->(name) { where(name: name) }
User.scope_sample(‘a’)
How to add a default scope?
default_scope { where(name: ‘d’) }
How to remove default scope?
User.unscoped
What the main callback do you know? ( 4 )
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 to add attribute options and convert types on a model level?
attribute :name, :integer, default: 10
Why do we need serialize in a model?
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 to use serialization?
serialize :description, Hash
# User.create(description: {a: 1 }) # creates "description", "---\n:a: 1\n" # User.last.description # => {:a=>1}
What is active_record store?
It’s the same as serialization
serialize :description, Hash
# or
store :description
What is enum?
Allows you to set a restriction for field values ( from speciific array)
How to add enum?
enum status: [:my_invalid, :my_valid]
add integer field to the db ( because it’s store only index)
How to set index explicitly to enum field?
enum status: { my_invalid: 0, my_valid: 1 }
How to use enum helpers? ( 3 ways )
class User < ApplicationRecord enum status: [:my_invalid, :my_valid] end
- check current status
# user.my_invalid? # user.my_valid?
- update status
# user.my_invalid! # user.my_valid!
- return scope
# User.my_invalid # returns all record with this status