39
38

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 でモデルの初期値を代入したい場合

Last updated at Posted at 2013-11-30

default_scopeには、初期値を代入する機能がある。(これ自体でハマることもある気がする)

しかし、default_scopeでの条件は個別には外せないので、避けたほうが無難。(unscopedで外せるけれど、これは全ての条件を消しさるので、has_many 等を介して呼んだ場合の条件も消えてしまう)

よくある?Rails失敗談 default_scope編 | TechRacho
http://techracho.bpsinc.jp/tsunekawa/2013_10_10/13553

なので、下記のようにする

class Model < ActiveRecord::Base
  after_initialize :set_default_value
  
  private
  def set_default_value
    self.number  ||= 0.0
    self.bool_field = true if (self.has_attribute? :bool_value) && self.bool_field.nil?
  end
end

参考:
ruby on rails - How can I set default values in ActiveRecord? - Stack Overflow
http://stackoverflow.com/questions/328525/how-can-i-set-default-values-in-activerecord

追記:
あとからデフォルト値を追加するときは、新規に限ったほうがよい??

after_initialize :set_default_value, if: :new_record?
39
38
1

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
39
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?