Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No possibility to update model attributes with a block syntax?

There is a block syntax for new and create that goes like this:

 user = User.create do |u|
    u.name = "David"
    u.mail = "[email protected]"
 end

Is there a block syntax that would be valid in Rails 3 and Rails 4 for updating attributes? Something like:

  user = User.where(name: "David").first

  user.update_attributes do |u|
    u.mail = "[email protected]"
  end

Maybe not update_attributes but something similar. I have been searching the web and the Rails 4 source on Github, and i think there isn't such a thing. Am I wrong?

P.S. i'm not looking for making any monkey patch methods or something similar, just interested if there is a method that comes by default with ActiveRecord.

like image 988
Zippie Avatar asked Aug 25 '13 12:08

Zippie


People also ask

How do you update a record in Ruby?

It's a three-step process. First, we find an object and create a new instance from it. Then we change the values on that instance. And then you save the revised object data to the database table.

What is Ruby ActiveRecord?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is Rails ApplicationRecord?

ApplicationRecord inherits from ActiveRecord::Base , which defines a number of helpful methods. You can use the ActiveRecord::Base.table_name= method to specify the table name that should be used: class Product < ApplicationRecord self.


1 Answers

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

user.tap do |u|
  u.mail = "[email protected]"
end
user.save

One caveat in Rails 3 is it avoids mass assignment protection compared to #update_attributes, which may or may not be what you want. In Rails 4 of course it doesn't matter because attributes are protected differently (using strong parameters).

like image 87
bobics Avatar answered Dec 22 '22 00:12

bobics