ruby-on-railsrails-console

Rails console update


Hello I was trying the update the data in the table using the rails console.

Box.where("code = 'learning'").update(duration: 10)

I ran this command.

The data is temporarily changing.

Box.where("code = 'learning'")

When I run this the precious data is being displayed.

Could anyone let me the issue. Thank you in advance.


Solution

  • #update updates a single record.

    user = User.find_by(name: 'David')
    user.update(name: 'Dave')
    

    It will return true/false depending on if the record was actually updated. You can see the validation errors by inspecting the errors object:

    user.errors.full_messages
    

    In non user-interactions situations like seed files and the console it can be helpful to use the bang methods such as #update!, #save! and #create! which will raise an exception if the record is invalid.

    If you want to update multiple records at once you need to use #update_all:

    Box.where("code = 'learning'")
       .update_all(duration: 10)
    

    This creates a single SQL update statement and is by far the most performant option.

    You can also iterate through the records:

    Box.where("code = 'learning'").find_each do |box|
      box.update(duration: 10)
    end
    

    This is sometimes necissary if the value you are updating must be calculated in the application. But it is much slower as it creates N+1 database queries.