I have a strange issue with to_json method in my Rails 3 app. (well at least I think it is to do with to_json)
In my controller, I am getting the list of all the libraries stored in the DB
@libraries = Library.where( "latitude IS NOT NULL AND longitude IS NOT NULL" )
And then I create a json file that contains the library information above.
my_file = File.new("public/javascripts/libraries.json", "w")
my_file.write "var libs = {'libraries' : "
my_file.write @libraries.to_json( :only => [ :id, :name, :address, :latitude, :longitude ])
my_file.write "};"
Then in my view, I display each library object on Google Map. In the view file, I am reading the json file by loading the libraries.json file as a javascript file.
Now the problem is that the library objects are displayed on Google map SOMETIMES, but not all the time, and through Firebug, I was able to determine that sometimes the “libs” variable, that is contained in the JSON file is “undefined”.
This makes me think that the file has not been completely being written, or the data in the file has not been completely been loaded. But I am not too sure what it is.
Does anyone have an idea what could be causing this?
Yes, it is probably caused by the fact that you write it to a file instead of just including it in a tag. Because what probably happens (sometimes) is that the server gets the request, writes the json file, then renders a view and sending that view to the client. The client is then told to load the libraries.json file resulting in another request to the server to retrieve that file. But what if that file in that exact moment is being rewritten because another client has sent a request at the same time? It will fail.
There are a few other ways you could go about this. First and probably the quickest to get up and running is to include this in your controller and view instead of writing to a file:
But a better solution would probably be to schedule some job or task to load the library from the database at schedule intervals and write to a json file perhaps once a day because I guess it is not really necessary to load these from the database all the time unless they change from one minute to the next.