【问题标题】:Initializing a hash variable when creating an instance创建实例时初始化哈希变量
【发布时间】:2010-12-06 11:48:15
【问题描述】:

当我创建 SomeClass 的实例时,我试图将类变量初始化为哈希,但我一直收到错误消息。对 ruby​​ 来说有点新,所以任何帮助都将不胜感激。谢谢

class SomeClass < ActiveRecord::Base  
  attr_accessible :some_hash  
  serialize :some_hash,   Hash  

  def initialize(args = {})  
    @some_hash != {}  
  end  
end

NoMethodError:未定义的方法has_key?' for nil:NilClass from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/whiny_nil.rb:52:inmethod_missing'
来自 /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2827:in has_attribute?'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2888:in
inspect'
来自 /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2887:in collect'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2887:in
inspect'
来自 /opt/local/lib/ruby/1.8/irb.rb:310:in output_value'
from /opt/local/lib/ruby/1.8/irb.rb:159:in
eval_input'
来自 /opt/local/lib/ruby/1.8/irb.rb:271:in signal_status'
from /opt/local/lib/ruby/1.8/irb.rb:155:in
eval_input'
来自 /opt/local/lib/ruby/1.8/irb.rb:154:in eval_input'
from /opt/local/lib/ruby/1.8/irb.rb:71:in
start'
来自 /opt/local/lib/ruby/1.8/irb.rb:70:in catch'
from /opt/local/lib/ruby/1.8/irb.rb:70:in
start'
来自 /opt/local/bin/irb:13

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    这个article 应该可以帮到你。

    在 Ruby 中,您可以通过简单地重新定义方法(“monkey patching”)轻松地覆盖 gems 中的现有代码

    这是你重写的#initialize 方法:

    # active_record/base.rb
      def initialize(attributes = nil)
        @attributes = attributes_from_column_definition
        @attributes_cache = {}
        @new_record = true
        @readonly = false
        @destroyed = false
        @marked_for_destruction = false
        @previously_changed = {}
        @changed_attributes = {}
    
        ensure_proper_type
    
        populate_with_current_scope_attributes
        self.attributes = attributes unless attributes.nil?
    
        result = yield self if block_given?
        _run_initialize_callbacks
        result
      end
    

    【讨论】:

      猜你喜欢
      • 2010-12-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2011-03-18
      • 2010-11-26
      相关资源
      最近更新 更多