본문 바로가기
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

http://www.davidverhasselt.com/set-attributes-in-activerecord/


Rails 4 allows the developer to change ActiveRecord attributes in various ways. Each one does it slightly differently with sometimes unique side-effects. It’s important you understand which method to use, so here’s a cheat sheet with in-depth information below.

This article has been updated for Rails 4. Check out the old Rails 3 version if you’re using that version.

Cheat Sheet

MethodUses Default AccessorSaved to DatabaseValidationsCallbacksTouches updated_atReadonly check
attribute=YesNon/an/an/an/a
write_attributeNoNon/an/an/an/a
update_attributeYesYesNoYesYesYes
attributes=YesNon/an/an/an/a
updateYesYesYesYesYesYes
update_columnNoYesNoNoNoYes
update_columnsNoYesNoNoNoYes
User::updateYesYesYesYesYesYes
User::update_allNoYesNoNoNoNo

In Depth

For the following examples we’ll set the name attribute on the user object.

user.name = "Rob"

This regular assignment is the most common and easiest to use. It is the default write accessor generated by Rails. The name attribute will be marked as dirty and the change will not be sent to the database yet.

You can undo the change by calling reload! or save the change to the database by calling save.

user.write_attribute(:name, "Rob")

This is the method that is called by the default accessor above. An alias for this method is user[:name] = "Rob". It also has a read_attribute counterpart.

Just like above, this method does not yet change the attribute in the database. Use this method anywhere you need to bypass the default write accessor above, for example when you want to write a custom attribute= writer:

def name=(new_name)
  write_attribute(:name, new_name.upcase)
  # This is equivalent:
  # self[:name] = new_name.upcase
end

user.update_attribute(:name, "Rob")

This method will change the attribute in the model and pass it straight to the database, without running any validations.

Two gotchas:

  • Any other changed attributes are also saved to the database.
  • Validations are skipped so you could end up with invalid data.

Because of that last quirk it’s a good practice to use update instead even though you might only want to update one attribute.

user.attributes = {name: "Rob"}

This method will set all the attributes you pass it. The changes are not saved to the database. Any attributes you don’t pass will be left unchanged. You can also use assign_attributes:

user.attributes = {name: "Rob", age: 12}
user.assign_attributes {name: "Rob", age: 12}

user.update(name: "Rob")

This method used to be called update_attributes in Rails 3. It changes the attributes of the model, checks the validations, and updates the record in the database if it validates.

Note that just like update_attribute this method also saves other changed attributes to the database.

user.update_columns(name: "Rob")

Much like User::update_all this executes a direct SQL UPDATE query and bypasses any validations or callbacks. It does check first if any of the columns are marked as readonlyand if so, raises an exception.

user.update_column(:name, "Rob")

This is equivalent to calling user.update_columns(name: "Rob") described above.

User.update(1, name: "Rob")

Note: this is a class method

This method finds the object with the specified ID and updates it’s attributes with the passed in hash. It uses the User#update method to do so, so just like that one it validates and runs callbacks, as well as touch the updated_at attribute.

You can also pass in an array of ID’s and parameters:

User.update(
  [1,2,3],
  [
    {name: "Rob"},
    {name: "David", age: 12},
    {age: 15, location: "London"},
  ]
)

User.update_all(name: "Rob")

Note: this is a class method

This method runs an SQL UPDATE query that updates the attributes of all objects without running any validations or callbacks. You can also call this method on a scoped relation:

User.where(name: "Robbie").update_all(name: "Rob")

More

If you want to understand more about these methods I suggest you check out their source code. Each time it’s only a couple of lines and it will really broaden your understanding of how Rails works!


Title
List of Articles
번호 제목 글쓴이 날짜 조회 수
» Different Ways to Set Attributes in ActiveRecord (attribute, create, update, validation) Hojung 2015.05.24 1358
30 Ruby Style Guide Hojung 2015.02.05 1740
29 Refresh content automatically after some period time on Rails Hojung 2015.01.22 2339
28 Install ruby-filemagic on Mac (brew, libmagic) Hojung 2014.12.03 1566
27 Byte manipulation in Ruby Hojung 2014.12.03 1517
26 How to use Github for your project file Hojung 2014.09.24 1162
25 Ruby map, each, collect, inject, reject, select quick reference Hojung 2014.06.10 1879
24 Difference between collect, select, map and each in ruby Hojung 2014.06.10 1388
23 remove nil from array (compact, compact!) Hojung 2014.06.10 1671
22 remove child association model when parent removed (rails-dependent-destroy) Hojung 2014.06.03 1737
21 deploying cron jobs with whenever gem Hojung 2014.06.01 1774
20 Get list of a class' instance methods Hojung 2014.06.01 1456
19 Optional method parameters in Ruby Hojung 2014.05.29 1550
18 Best Ruby On Rails Content Management Systems (CMS) Hojung 2014.04.26 2733
17 The simple way to print exceptions in Ruby Hojung 2014.04.07 1574
16 Ruby Symbols Hojung 2014.04.05 6350
15 What is the difference between a Symbol and String? Hojung 2014.04.05 1555
14 install Rbenv, ruby and rails Hojung 2014.03.22 1728
13 HTTP Posts in Ruby Hojung 2014.03.14 1733
12 optparse: mandatory and optional arguments example Hojung 2014.03.14 2418
Board Pagination ‹ Prev 1 2 Next ›
/ 2

Designed by sketchbooks.co.kr / sketchbook5 board skin

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5