LoginSignup
2
2

More than 3 years have passed since last update.

ActiveRecordでカラム名のメソッドをオーバーライドしたときに、カラムを参照する方法

Posted at

背景

モデルにDBのカラム名と同名のインスタンスメソッドを定義し、さらにそのメソッド内でカラムを参照したい

方法

2つ方法がある模様

class Person < ApplicationRecord
  def name
    self[:name]
  end

  def name
    read_attribute(:name)
  end
end

The Rails Style Guide では、self[:name]のほうをお勧めしている

参考

https://github.com/satour/rails-style-guide/blob/master/README-jaJA.md#read-attribute
https://stackoverrun.com/ja/q/5968719

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