Override ActiveRecord attribute methods

前端 未结 4 1866
臣服心动
臣服心动 2020-12-07 07:39

An example of what I\'m talking about:

class Person < ActiveRecord::Base
  def name=(name)
    super(name.capitalize)
  end
  def name
    super().downcas         


        
4条回答
  •  伪装坚强ぢ
    2020-12-07 08:18

    Echoing Gareth's comments... your code will not work as written. It should be rewritten this way:

    def name=(name)
      write_attribute(:name, name.capitalize)
    end
    
    def name
      read_attribute(:name).downcase  # No test for nil?
    end
    

提交回复
热议问题