タグ

ブックマーク / blog.sanojimaru.com (1)

  • ActiveRecordのattribute methodをオーバーライドするとき

    ActiveRecordのattributeメソッドをオーバーライドする場合、オーバーライド元のattributeを呼ぶには(read|write)_attributeを使う。 例えば、とあるモデルExampleのhogeという属性が空の場合に、fugaという属性の中身を代替として返したい場合。 class Example < ActiveRecord::Base def hoge read_attribute(:hoge) || fuga end def fuga read_attribute(:fuga) || 'なんもないっす' end end また、hogeに値をセットしたとき、fugaが空ならfugaにも同じ値をセットしたい場合。 class Example < ActiveRecord::Base def hoge=(value) write_attribute(:hoge,

    ActiveRecordのattribute methodをオーバーライドするとき
    akatakun
    akatakun 2015/08/04
    read(write)_attributeメソッド
  • 1