How to maintain static json file in rails?

I have a file on my server that is outside of my application directory. This is a text file containing a json object, /path/to/data.json .

What is the easiest way to serve this file in Rails, for example. return it in response to a GET request?

Here is what I have tried so far, inspired by this answer and others. (It may be off base - I'm new to rails.)

  • added this line to route.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 does not work. When I point 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?

+6
source share
3 answers

I think this is a problem with the area; your external @data do not match the @data in the method. That is, you cannot use instance variables, as expected, outside of methods, because there is no instance yet.

It should work if you use a class variable like

 @@data = File.read("/path/to/data.json") 

then

 render :json => @@data 
+11
source

Put it in public/assets/javascripts . Or app/assets/javascripts . The server may even return the correct content type.

+7
source
  • put the data.json file in the project directory (e.g. public / data.json)
  • @data = File.read ("# {Rails.root} /public/data.json")
  • Last but not least: json => @data li>
+4
source

Source: https://habr.com/ru/post/918716/


All Articles