Rails 4 to_json产生意外的异常nil不是符号

big*_*can 13 ruby activerecord ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我正在将Rails 3应用程序升级到Rails 4.在Rails 3中,包含ActiveRecord对象数组的哈希的json序列化正常工作; 现在在Rails 4中,它具有不可预测的结果.

这是一个TypeError Exception: nil is not a symbol在Rails 4上失败的示例对象

{1230 =>
  [
    #<QuestionAnswerResponse response_id: 127, response_set_id: 6, response_group: nil, question_data_export_identifier: "is_co_pi_involved", answer: "No", question_id: 1230, answer_id: 2077, response: "">, 
    #<QuestionAnswerResponse response_id: 131, response_set_id: 6, response_group: nil, question_data_export_identifier: "is_co_pi_involved", answer: "No", question_id: 1230, answer_id: 2077, response: "">
  ]
}
Run Code Online (Sandbox Code Playgroud)

现在如果我采取另一个类似的对象; hash包含一个ActiveRecord对象数组并运行to_json它适用于这个...

{1234 =>
  [
    #<Response id: 1, response_set_id: 2, question_id: 4, answer_id: 2, datetime_value: nil, integer_value: nil, float_value: nil, unit: nil, text_value: nil, string_value: nil, response_other: nil, response_group: nil, created_at: "2014-05-30 21:17:23", updated_at: "2014-05-30 21:17:23", survey_section_id: 1, api_id: "f44b22ba-a93b-477f-8a7f-c5b4566338f0", attach_file_name: nil, attach_content_type: nil, attach_file_size: nil, attach_updated_at: nil>, 
    #<Response id: 2, response_set_id: 2, question_id: 10, answer_id: 10, datetime_value: nil, integer_value: nil, float_value: nil, unit: nil, text_value: "test", string_value: nil, response_other: nil, response_group: nil, created_at: "2014-05-30 21:17:23", updated_at: "2014-05-30 21:17:23", survey_section_id: 1, api_id: "e7fa8aa2-6e47-4f88-8802-949fdc902a2e", attach_file_name: nil, attach_content_type: nil, attach_file_size: nil, attach_updated_at: nil>
  ]
} 
Run Code Online (Sandbox Code Playgroud)

big*_*can 19

支持我的QuestionAnswerResponse模型的视图没有id列,我没有在模型中设置主键.在我使用此模型的能力中,我不需要主键; 这是一个只读视图,用于直接访问某些复杂的键/值配对,而不是通过更复杂的逻辑.

在Rails 3中,这很好用; 在Rails 4中,当您访问没有主键的模型时,您最终会得到一个在哈希中看起来像这样的属性nil => nil

问题实际上是在ActiveRecord级别,但在我尝试执行json序列化之前实际上并没有引起问题; 在哪个时间点尝试调用nil.to_sym来引发异常.

这似乎是ActiveRecord中的一个错误; 但是现在我通过在我的模型上手动设置主键来解决它.

  • 将"self.primary_key =:id#或其他主键"添加到模型中.谢谢! (6认同)