| 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') | 
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