hiyoko-programingの日記

プログラミングを勉強したてのひよっ子。   エンジニア目指して勉強中。

Rails Drill 問題10

必要となる知識

テーブルに保存されているレコードは、

インスタンスの取得」 → 「インスタンスのカラムの更新」という流れで特定のインスタンスのカラムの値を更新することができる。

属性値の更新には、 update というメソッドを利用する。

updateメソッドの引数は、(カラム名: 更新したい値, カラム名: 更新したい値・・・)とする。

コンソール
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# レコードの取得
pry(main)> tweet = Tweet.find(1)
=> #<Tweet id: 1, name: "keita", image: "http://image.jpg", text: "rails now. it's so fun!!", created_at: "2015-01-12 07:55:38", updated_at: "2015-01-12 07:55:38">
# レコードのカラムの値の更新
pry(main)> tweet.update(text: "Rails is beautiful!!")
=>   (1.0ms)  BEGIN
  SQL (2.3ms)  UPDATE `tweets`
    中略
   (12.0ms)  COMMIT
=> true
# カラムの値が更新されている
pry(main)> tweet.text
=> "Rails is beautiful!!"

 Drill問題3で生成したインスタンスを以下の条件で更新する。

カラム
textカラム 「update is beautiful」という文字列
imageカラム 「 http://update.jpg 」という文字列

実行例

コンソール
1
2
3
4
5
pry(main)> #問題3で生成したインスタンスを取得するコマンドを打ってください。
=> #<Tweet id: 8, name: "keita", image: "http:://happy_boy.jpg", text: "i am happy boy!", created_at: "2015-01-12 11:53:49", updated_at: "2015-01-19 08:36:55">

pry(main)> #問題3で生成したインスタンスを更新するコマンドを打ってください。
=> #<Tweet id: 8, name: "keita", image: "http://update.jpg", text: "update is beautiful", created_at: "2015-01-12 11:53:49", updated_at: "2015-01-12 11:53:49">

解説

 

解答例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
pry(main)> tweet = Tweet.find(8)
=> #<Tweet id: 8, name: "keita", image: "http://happy_boy.jpg", text: "i am happy boy!", created_at: "2015-01-12 11:53:49", updated_at: "2015-01-12 11:53:49">
#更新したいレコードを取得

pry(main)> tweet.update(text: "update is beautiful", image: "http://update.jpg")
=> true

pry(main)> tweet
=> #<Tweet id: 8, name: "keita", image: "http://update.jpg", text: "update is beautiful", created_at: "2015-01-12 11:53:49", updated_at: "2015-01-19 08:36:55">
 #レコード更新

解説

updateメソッドはインスタンス.update(カラム名1: "更新したい値1", カラム名2: "更新したい値2")というように使い、既にデータベースに保存されているレコードを更新することが出来る。