0
votes

I find myself writing this kind of pattern a lot. It's really ugly and annoying especially if I'm just running a quick change in Console.

u = User.find(some_id)
u.name = "new name"
u.save

What's the best way to make it so that I can do this in a single statement. I want to be able to do something like this instead.

User.find(some_id).set({name:"new nane"}).save

1
I think, find and update are dependent on each other. At least in this context, where you want to find the record and then only update the attributes. what if the record is not present? Do you still want to try updating the attributes? probably not and maybe that's why Rails doesn't have find_and_update_by as a method on ActiveRecord. Rails has find_or_create_by which makes sense cause if the record is not found, you want to create it with given attributes. - Abhinay
Also, running User.find(..) gives you more control over the code flow. you may choose to not execute the rest of the code and exit immediately if the record is not found. whereas in case of something like find_and_update_by (method not present) you are forced to run update even when the record is not present. - Abhinay
you can chain like User.find(some_id).update(name: 'new name', other_attribute: 'abc') - Amit Patel
Since nobody has mentioned it, update_all does what you’re describing, a single SQL statement to update multiple records. E.g. User.where(‘age > 50’).update_all(admin: true). Warning, skips validations. apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all - AJFaraday

1 Answers

1
votes

This should work fine

User.find_by(id: some_id)&.update_attributes(name: 'abc', second_attribute: 'some_value')