Frequently used methods in Active Record

Methods used in ActiveRecord

Method role Return value Description example
valid? Check if the target object is valid true or false user.valid?
save Have the database save the target object true or false user.save
create Generate and save the model at the same time Success: the object itself
Failure: Error
User.create(name: 'hoge', email: 'fuga')
destroy Delete the target object Success: the object itself
Failure: Error
user.destroy
find Get record from database with id in argument Success: Target object
Failure: Error
User.find(1)
find_by Get the record from the database with key and value as arguments Success: the object itself
Failure: nil
User.find_by(name: 'hoge')
update Pass the hash of the attribute to update the value in the database Success: true or failure: error user.update(name: 'hoge', email: 'fuga')
update_attribute Update only specific attributes
Key for the first argument, value for the second argument
Can be updated by ignoring the verification conditions
Success: true or failure: error user.update_attribute(:name, 'piyo')

Usage pattern

The return value of the save method will be true or false, so it will be used when implementing the controller's create action.

hoge_controller.rb


def create    
  tweet = Tweet.create(tweet_params)
  if tweet.save
    #Processing when saving is successful
  else
    #Processing when saving fails
  end
end

Recommended Posts

Frequently used methods in Active Record
Frequently used processes in SpreadSheet
About methods often used in devise
Ruby methods often used in Rails
List of methods used in PAIZA D rank
Summary of frequently used commands in Rails and Docker
Frequently used docker-compose command
Docker Frequently used commands
Active Record, complex queries
Dynamically call methods in JSF
About validation methods in JUnit
IntelliJ Frequently Used Operation Notes
Helper methods available in devise
Gem often used in Rails
Test private methods in JUnit
rails console Frequently used operations
Matcher often used in RSpec
Frequently used Maven command collection
Mock static methods in Mockito 3.4
What is Rails Active Record?