I have a file on my server that's outside of my app directory. It's a text file that holds a json object, /path/to/data.json
.
What's the simplest way to serve this file in Rails, e.g. to return it in response to a GET request?
Here's what I've tried so far, inspired by this answer and others. (This may be way off-base -- I'm new to rails.)
added this line to routes.rb
resources :data
Wrote the following data_controller.rb
class DataController < ApplicationController
@data = File.read("/path/to/data.json")
def index
render :json => @data
end
end
This doesn't work. When I direct my browser to http://myserver.com/data.json I just see "null" instead of the data.json
file.
Any idea what I'm doing wrong?
I think this is a scope issue; your outer @data is not the same as the @data in a method. That is, you can't use instance variables as expected outside of methods because there is no instance yet.
It should work if you use a class variable, eg
@@data = File.read("/path/to/data.json")
then
render :json => @@data
Put it in public/assets/javascripts
. Or app/assets/javascripts
. The server may even return the correct content-type.
data.json
file into your project directory ( for example public/data.json
)@data = File.read("#{Rails.root}/public/data.json")
:json => @data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With