Updating user objects

更新資料有兩種方法,一種是個別指定屬性值,然後再儲存:

> user
=> #<User id: 1, name: "Luffy Wang", email: "[email protected]", created_at: "2016-03-06 07:31:20", updated_at: "2016-03-06 07:31:20">
> user.email = "[email protected]"
=> "[email protected]"
> user.save
=> true

如果最後沒有使用 save 方法存進資料庫,那最後資料不會被更新到資料庫裡面:

> user.email
=> "[email protected]"
> user.email = "[email protected]"
=> "[email protected]"
> user.reload.email
=> "[email protected]"

儲存成功之後,updated_at 的值也會跟著更新:

> user.created_at
=> Sun, 06 Mar 2016 07:31:20 UTC +00:00
> user.updated_at
=> Sun, 06 Mar 2016 15:40:45 UTC +00:00

第二種更新資料的方法是 update_attributes,可以同時更新好幾筆屬性值:

> user.update_attributes(name: "Salt", email: "[email protected]")
=> true
> user.name
=> "Salt"
> user.email
=> "[email protected]"

update_attributes 方法,會同時進行更新和儲存的動作,成功就回傳 true。如果有任何驗證失敗,update_attributes 就會執行失敗。

如果只想更新一個屬性值,可以使用單數的 update_attribute,跳過驗證機制:

> user.update_attribute(:name, "The Dude")
=> true
> user.name
=> "The Dude"