在Rails中覆盖初始化方法到模型

时间:2013-08-02 15:11:09

标签: ruby-on-rails activerecord ruby-on-rails-4 object-initializers

我正在尝试覆盖initialize方法。见下文

class Restriction < ActiveRecord::Base
  RESTRICTION_TYPES = {
    less_than: "IND<X", 
    greater_than: "X<IND", 
    between: "X<IND<Y"
  }

  def initialize restriction_type_name
    super
    formula = RESTRICTION_TYPES[restriction_type_name]
  end

  private
  def formula=f
    self[:formula] = f
  end

end

当我运行r = Restriction.new(:between)时,我得到例外:

NoMethodError: undefined method `stringify_keys' for :between:Symbol

我做错了什么?

BTW我这样做是因为formula属性无法从外部加入。

1 个答案:

答案 0 :(得分:0)

你无法覆盖initialize,你无论如何都无法工作(它会尝试在initialize方法中设置一个名为formula的局部变量)。但是,您可以将条件移动到formula= setter中,因此它的内容如下:

def formula=(restriction_type_name)
  self[:formula] = RESTRICTION_TYPES[restriction_type_name]
end