Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 to_json produces unexpected Exception nil is not a symbol

I am in the process of upgrading a Rails 3 application to Rails 4. In Rails 3 the json serialization of a hash containing an array of ActiveRecord objects was working correctly; now in Rails 4 it is having unpredictable results.

Here is an example object that fails with TypeError Exception: nil is not a symbol on 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: "">
  ]
}

Now if I take another similar object; hash containing an array of ActiveRecord objects and run to_json it works on this one...

{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>
  ]
} 
like image 610
bigtunacan Avatar asked Jun 20 '14 14:06

bigtunacan


1 Answers

The view backing my QuestionAnswerResponse model does not have an id column and I was not setting a primary key in the model. In the capacity that I use this model I do not need a primary key; this is a read only view used to more easily access some complex key/value pairings directly instead of through more complex logic.

In Rails 3 this worked fine; in Rails 4 when you access a model without a primary key you end up with an attribute that looks like this in your hash nil => nil

The problem is actually up at the ActiveRecord level, but wasn't actually causing a problem until I attempt to do json serialization; at which point in time an attempt is made to call nil.to_sym which raises the exception.

This seems like a bug in ActiveRecord to me; but for now I have worked around it by manually setting a primary key on my model.

like image 79
bigtunacan Avatar answered Nov 16 '22 19:11

bigtunacan