Closed Komei22 closed 7 years ago
irb(main):065:0> user.name = "hoge" => "hoge" irb(main):066:0> user.name => "hoge" irb(main):067:0> user.save
irb(main):069:0> user.update_attributes(email: "hogehoge@example.com") (0.2ms) SAVEPOINT active_record_1 SQL (1.1ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", "hogehoge@example.com"], ["updated_at", "2017-06-28 06:06:20.149017"], ["id", 1]] (0.2ms) RELEASE SAVEPOINT active_record_1 => true irb(main):070:0> user.save (0.2ms) SAVEPOINT active_record_1 (0.1ms) RELEASE SAVEPOINT active_record_1 => true irb(main):071:0> user => #<User id: 1, name: "hoge", email: "hogehoge@example.com", created_at: "2017-06-28 05:36:33", updated_at: "2017-06-28 06:06:20">
=> #<User id: 1, name: "hoge", email: "hogehoge@example.com", created_at: "2017-06-28 05:36:33", updated_at: "2017-06-28 06:06:20"> irb(main):073:0> user.update_attributes(created_at: 1.years.ago) (0.1ms) SAVEPOINT active_record_1 SQL (0.3ms) UPDATE "users" SET "created_at" = ?, "updated_at" = ? WHERE "users"."id" = ? [["created_at", "2016-06-28 06:08:23.523299"], ["updated_at", "2017-06-28 06:08:23.528045"], ["id", 1]] (0.1ms) RELEASE SAVEPOINT active_record_1 => true irb(main):074:0> user => #<User id: 1, name: "hoge", email: "hogehoge@example.com", created_at: "2016-06-28 06:08:23", updated_at: "2017-06-28 06:08:23">
ch 6.1.5演習
演習1
userオブジェクトへの代入を使ってname属性を使って更新し、saveで保存してみてください。
演習2
今度はupdate_attributesを使って、email属性を更新および保存してみてください。
演習3
同様にして、マジックカラムであるcreated_atも直接更新できることを確認してみてください。ヒント: 更新するときは「1.year.ago」を使うと便利です。これはRails流の時間指定の1つで、現在の時刻から1年前の時間を算出してくれます。