LoginSignup
2
2

More than 5 years have passed since last update.

Rails4 | 新規・変更機能 | update_columns の追加

Posted at

Rails4 | 新規・変更機能 | update_columns の追加

概要

update_columnsupdate (旧 update_attributes ) よく似たメソッドで、
対象カラムを変更する点は同じですが、 validationhook を実行しません。

サンプル

仕様

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

サンプルコード

  • scaffold した状態の PeopleControllerupdate メソッドの内容を下記のように変更します
def update
  respond_to do |format|
    if @person.update_columns(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_columns を実行

更新が反映されているが、 before_update フックが呼び出されていないことをログから確認できます。

2
2
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
2
2