Is it possible to alter a record in rails, without first reading it

Rails models have the update method, which does a SQL select then an SQL update.

Its use is simple (suppose you have a model named Person)

Person.update(person_id, :user_name => 'New Name')

The drawback is that you have to know beforehand the person id.

But then, you will always have to do a query to find out that. You could write your own SQL to change the column value, with a WHERE clause that searches for the param you have.

Rails models have the update_all method, which does only a SQL update without loading the data. But I wouldn't recommend using it because it doesn't trigger any callbacks or validations that your model may have.

You could use the update_all like this:

Book.update_all "author = 'David'", "title LIKE '%Rails%'"

ps: examples were all taken from the Rails official documentation. If you search for update, or update_all, you'll find both methods in no time.

Take a look there, it's a good place to find out what rails can do.

Rails API link


It's not obvious from the documentation, but update_all is the answer to this question.

Book.where(id: 123).update_all(title: "War and Peace")

results in exactly one query:

UPDATE `books` SET `books`.`title` = "War and Peace" WHERE `books`.`id` = 123

It's been a while since this question was asked, but this is so for Rails 4/5/6.