문제

I'm trying to override the initialize method. 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:

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.

도움이 되었습니까?

해결책

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). You can, however, move the conditions into your formula= setter, so it reads like:

def formula=(restriction_type_name)
  self[:formula] = RESTRICTION_TYPES[restriction_type_name]
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top