Sachin srinivasan Sachin srinivasan - 1 year ago 60
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
tempJson = @events.to_json.html_safe
aFile ="events.json", "r+")

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) {

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 Source

You have to write the file to public/ directory. You can achieve this by doing: + 'public/events.json', 'w+')

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


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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download