【问题标题】:Rails 4 to_json produces unexpected Exception nil is not a symbolRails 4 to_json 产生意外的异常 nil 不是符号
【发布时间】:2014-06-20 14:01:15
【问题描述】:

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

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

{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: "">
  ]
}

现在,如果我再拿一个类似的物体;包含 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>
  ]
} 

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-4


    【解决方案1】:

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

    在 Rails 3 中这很好用;在 Rails 4 中,当您访问没有主键的模型时,您最终会在哈希 nil =&gt; nil

    中得到一个看起来像这样的属性

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

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

    【讨论】:

    • self.primary_key = :id # or other primary key 添加到模型中有效。谢谢!
    • 非常有帮助,谢谢。我有一个没有主键的旧表,所以我只是使用composite_primary_keys 来指定应该是唯一的列组合。
    猜你喜欢
    • 2011-04-16
    • 2013-03-26
    • 2011-07-29
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多