読者です 読者をやめる 読者になる 読者になる

has_manyで所有側がpushするとエラー

rails
NoMethodError in MemochonController#update

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]=

/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1974:in `write_attribute'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1657:in `[]='
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations/association_proxy.rb:105:in `set_belongs_to_association_for'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations/has_many_association.rb:162:in `insert_record'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations/association_collection.rb:26:in `<<'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations/association_collection.rb:23:in `<<'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/abstract/database_statements.rb:59:in `transaction'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:95:in `transaction'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:121:in `transaction'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations/association_collection.rb:22:in `<<'

とのことなのでデバッグ文を埋め込んでみると

      def write_attribute(attr_name, value)                                                                                  
        attr_name = attr_name.to_s                                                                                           
puts "attr_name [#{attr_name}]"                                                                                              
        if (column = column_for_attribute(attr_name)) && column.number?                                                      
          @attributes[attr_name] = convert_number_column_value(value)                                                        
        else                                                                                                                 
          @attributes[attr_name] = value                                                                                     
        end                                                                                                                  
      end  
-------------------------------------------
attr_name [date]
attr_name [year]
attr_name [memo_id]

attr_name[memo_id]は被所有側のカラムで、それにwriteしようとしているみたい。
とりあえずここで中断。

再開。
ruby-debugを知ったので使ってみる。

# gem install ruby-debug

して、

require 'ruby-debug'
      :
debugger
      :

わーい、gdbみたい。