Home > Mobile >  Can't read JSON file in Ruby on Rails
Can't read JSON file in Ruby on Rails

Time:10-11

I am new in ruby on rails and I want to read data from a JSON file from a specified directory, but I constantly get an error in chap3(File name)

Errno::ENOENT in TopController#chap3. No such file or directory @ rb_sysopen - links.json.

In the console, I get a message

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

How I can fix that?

Code:

require "json"
class TopController < ApplicationController
  def index
    @message = "おはようございます!"
  end

 def chap3
  data = File.read('links.json')
  datahash = JSON.parse(data)
  puts datahash.keys
 end
 
def getName
  render plain: "名前は、#{params[:name]}"
end

def database
  @members = Member.all
end
end

JSON file:

{ "data":  [
    {"link1": "http://localhost:3000/chap3/a.html"},
    {"link2": "http://localhost:3000/chap3/b.html"},
    {"link3": "http://localhost:3000/chap3/c.html"},
    {"link4": "http://localhost:3000/chap3/d.html"},
    {"link5": "http://localhost:3000/chap3/e.html"},
    {"link6": "http://localhost:3000/chap3/f.html"},
    {"link7": "http://localhost:3000/chap3/g.html"}]}

CodePudding user response:

Rails use the content of file in the controller

 @data = File.read("#{Rails.root}/app/controllers/links.json")

CodePudding user response:

I would change these two lines

data = File.read('links.json')
datahash = JSON.parse(data)

in the controller to

datahash = Rails.root.join('app/controllers/links.json').read

Note: I would consider moving this kind of configuration file into the /config folder and creating a simple Ruby class to handle it. Additionally, you might want to consider paths instead of URLs with a host because localhost:3000 might work in the development environment but in production, you will need to return non-localhost URLs anyway.

  • Related