ActiveRecord methods Flashcards
What is ActiveRecord pattern?
Maps one domain class to one database table, and one instance of that class to each row of that database.
How to use another table and primary_key for a model?
class Cat < ApplicationRecord self.table_name = 'animals' self.primary_key = 'id' end
How to set a default value for the field on model level?
class Cat < ApplicationRecord attribute :name, :string, default: 'Default' end
How to return the first record of a model or create a new one if the first doesn’t exist?
Cat.first_or_initialize(name: ‘d’) # new
Cat.first_or_create(name: ‘a’) # create
How to find records by an array of ids?
Cat.find([1,2])
How to rewrite the field method in the model? ( name for example)
def name
read_attribute(:name) + “!!!”
end
How to return a record attributes like a hash?
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 does The Query cache work?
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 to turn on cache manually?
Cat.cache do puts Cat.first puts Cat.first puts Cat.first end
will run only the first request, others will be cached
How to decrement, increment, or toggle the field?
Cat.last.increment!(:age)
Cat.last.decrement!(:age)
Cat.last.toggle!(:alive)
and the same without !
How to update a record and set updated_at with current time?
Cat.last.touch
How to show SQL query which rails method triggers?
Cat.where(id: 2).explain
# or
Cat.where(id: 2).to_sql