No way to update model attributes using block syntax?

There is a block syntax for new and create, which looks like this:

user = User.create do |u| u.name = "David" u.mail = " dhh@rails.com " end 

Is there a block syntax that will be valid in Rails 3 and Rails 4 for updating attributes? Sort of:

  user = User.where(name: "David").first user.update_attributes do |u| u.mail = " dhh@rubyonrails.com " end 

Maybe not update_attributes , but something like that. I searched the web and the source for Rails 4 on Github, and I think this is not happening. I am wrong?

PS I'm not looking for any methods for patch monkeys or something like that, just wondering if there is a method that comes with ActiveRecord .

+4
source share
1 answer

Use # tap (available since Ruby 1.9) if you want block syntax:

 user.tap do |u| u.mail = " dhh@rubyonrails.com " end user.save 

One caveat in Rails 3 is to avoid mass assignment protection compared to #update_attributes , which may or may not be what you want. In Rails 4, of course, this does not matter, since attributes are protected in different ways (using strong parameters).

+5
source

Source: https://habr.com/ru/post/1498827/


All Articles