Sachin srinivasan Sachin srinivasan - 12 days ago 5
JSON Question

how to read a file created in rails using javascript within new.html.erb

I have this method in rails where i am creating external events.json file.

def new
@event=Event.new
@users=User.all
@events=@user.events
tempJson = @events.to_json.html_safe
aFile = File.new("events.json", "r+")
aFile.syswrite(tempJson)
end


now events.json file is created in my app directory.
In my new.html.erb, how to access this file via javascript and set it to a variable?

<script type="text/javascript">
$.getJSON("events.json", function(json) {
debugger;
console.log(json);
});
</script>


I tried this.. and i get this error message when i inspect,

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/users/14/events/events.json

vl3 vl3
Answer

You have to write the file to public/ directory. You can achieve this by doing:

File.new(Rails.root + 'public/events.json', 'w+')

Then, you can access the file in your view doing:

$.getJSON("/events.json")

But i think that the best way to achieve this is by having an EventsController with and index action that responds in json.

class EventsController < ApplicationController
  def index
    @events = Event.all
    respond_to do |format|
      format.json { render json: @events}
    end
  end
end