10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails4 | 新規・変更機能 | update_attributes が update に変更

Posted at

Rails4 | 新規・変更機能 | update_attributes が update に変更

概要

update_attributesupdate というシンプルな名前に変更になりました。
ただし、 update_attributes は今まで通り使用可能。

サンプル

仕様

  • 下記で scaffold した状態をベースとする
rails g scaffold person name:string age:integer
rake db:migrate

サンプルコード

  • scaffold した状態の PeopleControllerupdate メソッドの内容を確認します
def update
  respond_to do |format|
    if @person.update(person_params)
      format.html { redirect_to @person, notice: 'Person was successfully updated.' }
      format.json { render :show, status: :ok, location: @person }
    else
      format.html { render :edit }
      format.json { render json: @person.errors, status: :unprocessable_entity }
    end
  end
end
  • Personモデルに before_update の設定を追加します
class Person < ActiveRecord::Base
  before_update ->{ logger.info 'before_update' }
end

update を実行

更新が反映され、ログで before_update フックの呼び出しを確認します。
以下は、フックのログ。

before_update
10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?