LoginSignup
0
1

More than 1 year has passed since last update.

ActiveRecordのattributes系メソッドは自動で型変換が行われる

Last updated at Posted at 2021-05-20

初めて知ったことだったので、知見として残しておきます

データ更新時にuserにデータを格納して、それを使って処理を行う必要があるとします

hoge_controller.rb
class HogeController < ApplicationController

  ~(中略)~

  def update
    user = assign_attributes(user_params) # user_paramsは strong_parametersです
    hoge = Hoge(user, current_user)
    if user.valid? && user.save
      p "更新成功!"
    else
      p "更新失敗!"
    end
  end
end
user.rb
class User < ApplicationRecord
  # name String
  # age  Integer
  # ageが正規表現で文字列等を弾いてないことが重要
  with_options presence: true do
    validates :name
    validates :age
  end
end

このとき、Userの入力フォームでageに対して文字列を入力した場合、更新成功!が出力されてage: 0の状態で登録されます
これは単一指定のattributeでも同様の現象が発生します

理由はattributesやassign_attributesを使ってカラムにデータを登録した際、元となるattribute内でwrite_attributeによるキャストが行われるから、ということでした
attributesは内部的にはassign_attributesと同一ですので結果は同じになります

こちらのQiita記事により詳しい解説が載っておりました

まとめ

数値型のカラムに対してはちゃんとformatの記載をしよう!

0
1
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
0
1