4

I am at a loss as to why this is happening. I have the following function:

def as_json(options = {}) json = { :id => id, # ... more unimportant code } unless options[:simple] # ... more unimportant code end json end 

It works most of the time, but in one particular partial where I call this:

window.JSONdata = <%= @day.to_json.html_safe %> 

I get the following error:

ActionView::Template::Error (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.[]):

Pointing to the line "unless options[:simple]". As far as I can tell, the options hash is nil - thus the method is ignoring the default param assignment. WHY? I can fix this by changing the method to:

def as_json(options) options ||= {} json = { :id => id, # ... more unimportant code } unless options[:simple] # ... more unimportant code end json end 

Does this make any sense to anyone!? Most appreciative for your help.

1 Answer 1

3

This is because you're using to_json, which has a default options of nil. to_json will eventually call as_json and pass the nil as options.

Here's where it happens on the Rails source code. First, to_json is defined with the default options of nil.

# https://github.com/rails/rails/blob/v3.0.7/activesupport/lib/active_support/core_ext/object/to_json.rb#L15 def to_json(options = nil) ActiveSupport::JSON.encode(self, options) end 

Eventually it will arrive here.

# https://github.com/rails/rails/blob/v3.0.7/activesupport/lib/active_support/json/encoding.rb#L41 def encode(value, use_options = true) check_for_circular_references(value) do jsonified = use_options ? value.as_json(options_for(value)) : value.as_json jsonified.encode_json(self) end end 

As you see, as_json is called with value.as_json(options_for(value)) and options_for(value) will return the default value of to_json, which is nil.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks so much for the great response - it was really clear and informative!
One last question. I tried calling to_json using the console before I posted this question to see if the issue was with that function. However in the console, both to_json and as_json worked fine. Any idea why the console didn't generate the error?
It behaves as expected on console for me. Maybe you didn't reload or restart the console to reflect the code at that moment.
Your probably right about reload. Thanks again for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.