简体   繁体   English

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

[英]Overriding initialize method into model in Rails

I'm trying to override the initialize method. 我正在尝试覆盖initialize方法。 See below 见下文

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

When I run r = Restriction.new(:between) I get the exception: 当我运行r = Restriction.new(:between) ,出现异常:

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

What am I doing wrong? 我究竟做错了什么?

BTW I'm doing this due to formula attribute can't be acceded from outside. BTW我这样做是由于formula属性不能从外部加入。

You can't override initialize , and what you have wouldnt work anyway (it would try to set a local variable called formula in the initialize method). 您不能覆盖initialize ,无论如何您都无法工作(它将尝试在initialize方法中设置一个称为formula的局部变量)。 You can, however, move the conditions into your formula= setter, so it reads like: 但是,您可以将条件移至您的formula= setter中,其内容如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM