LoginSignup
7
7

More than 5 years have passed since last update.

Railsで変更不可な導出カラムを設定する

Posted at

例えば、こんなモデル

Circle:円形
 - radius: 半径
 - square: 面積 # このカラムは半径から導出したいので、直接変更できないようにしたい
class Circle < ActiveRecord::Base
  def radius=(radius)
    super
    self[:square] = radius*radius*Math::PI
  end

  def square=(square)
  end
end

ポイント

  • squareのセッターメソッドを無効化
  • radiusのセッターメソッドでsquareを計算
  • squareにアクセスするにはself[:square]を用いる
7
7
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
7
7