17
13

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.

Railsでformから送ったパラメータをenum用にint型に変換する

Last updated at Posted at 2017-06-05

enum型は便利だけどフォームには不便

データベースでは整数型で保存してくれるけど、普段は文字列みたいに扱えるenum型。これをフォームで利用しようとしたんだけど、"2"は整数じゃないです、みたいなエラーでできなかった(当たり前)

パラメータを送るときのオプションで整数型に変換できないのかな〜、とか思ったけどどうやらなさ気だったんで、コントローラー側で変換することに。

整数に変換したいのは整数にできるやつだけ

フォームから何かを送信する時に普通にstring型のままでいいのも一緒に送信することもあると思うので、整数できるものだけを変換します。

当たり前ですが、全部の値をいきなり、to_iしたらエラーになるので。そもそも整数にできるか調べます。

def integer_string?(str)
   Integer(str)
   true
 rescue ArgumentError
   false
end

http://taro-tnk.hatenablog.com/entry/2012/12/17/001552
こちらのブログを参考にさせてもらいました。

そんでもって然るべきコントローラーのprivate部分にこんなのを用意します。

xxx_controller.rb
def params_int(model_params)
    model_params.each do |key,value|
      if integer_string?(value)
        model_params[key]=value.to_i
      end
    end
end

これで@model.update(params_int(model_params))みたいに使えば、無事int型になります。

その他注意

関係ないですが当時、気が狂っていたのか、カラムをstring型に指定していたため、何回やり直してもnilのままで値を入れることができませんでした。integerに指定しておきましょう。

17
13
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
17
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?