[Ruby] Methods often used in Active Record

1 minute read

Methods used in ActiveRecord

| Method | Role | Return value | Description example | |:–|:–|:–|:–| |valid? | Check if the target object is valid | true or false | user.valid? | save | Save target object in database | true or false | user.save | create | Generate and save model at the same time | Success: Object itself
Failure: Error | User.create(name:’hoge’, email:’fuga’) | destroy | Delete target object | Success: Object itself
Failure: Error | user.destroy | | find | Put id in the argument to get the record from the database | Success: target object
Failure: error | User.find(1) | | find_by | Put the key and value in the argument and fetch the record from the database | Success: Object itself
Failure: nil | User.find_by(name:’hoge’) | update | Pass the attribute hash to update the database value | Success: true or Failure: error | user.update(name:’hoge’, email:’fuga’) | | update_attribute | Update specific attributes only
key as the first argument, value as the second argument
Can be updated by ignoring the validation condition | Success: true or Failure: error | user.update_attribute(: name,’piyo’) |

Usage pattern

It is used when implementing create action of controller because the return value of save method is true or false

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