I've found a strange (to me) response from rails if I try to render
output as json, whereas xml is fine. From the logs. For example, here
are the logs for a simple query (from the browser) to list all "jobs":
Started GET "/jobs.json" for 127.0.0.1 at 2011-01-05 16:44:45 +0000
Processing by JobsController#index as JSON
Completed 406 Not Acceptable in 11ms
Started GET "/jobs.xml" for 127.0.0.1 at 2011-01-05 16:48:11 +0000
Processing by JobsController#index as XML
Completed 200 OK in 13ms (Views: 1.9ms)
The code being called is much the same:
def index
@jobs = Job.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @jobs }
format.json { render :json => @jobs }
end
end
Is this some dreadful misunderstanding on my part as to how rails 3
works, or is something else at work here?
I've found a strange (to me) response from rails if I try to render
output as json, whereas xml is fine. From the logs. For example, here
are the logs for a simple query (from the browser) to list all "jobs":
Probably because the browser has indicated (via the Accept header)
that text/xml is fine, but that json isn't. Can you inspect the
headers to see whether or not this is the case?
I've tested it with curl and I get the same result, even after setting
the headers correctly as mentioned above. Originally I thought that I'd
made an error with my curl configuration, but it appears that that is
not the case.
curl -i -X POST -H 'Content-Type: application/json' -H 'Accept:
application/json' -d '{---json in here--}'
http://127.0.0.1:3000/jobs.json
Strangely, I am able to get a response if I try accessing an individual
job id as json format:
Started GET "/jobs/4d2325fd35d31015fa000001.json" for 127.0.0.1 at
2011-01-07 13:35:57 +0000
Processing by JobsController#show as JSON
Parameters: {"id"=>"4d2325fd35d31015fa000001"}
Completed 200 OK in 13ms (Views: 2.0ms)
Therefore, it would seem to be something about the index method above
that is dodgy. However, if xml is requested from that method then the
406 error is not produced.
It appears that I might have found a fix, by including:
require "active_support/json"
…in config/application.rb.
Apparently the app wasn't able to render json at all, hence the errors
mentioned above. However, as I was using MongoDB I didn't immediately
notice this, as the data I saw displayed looked like it had been
rendered in JSON by rails.
I suspect that it is indeed something to do with mongo_mapper, but I
have no idea what as its not something I've tried using before. If it
actually worked it would be ideal for what I need...
By the way, after adding the line mentioned above I was able to
successfully render the output as JSON. However, attempts to create new
database entries (posting JSON to the jobs controller) ran into what
appears to be this bug: