0

I am new to ROR, I have some seed data stored in my database table and a YAML file. I have been loading the yaml file and converting it into a JSON which I parsed and displayed to the client.

Something like this.

controller.rb

def template_library
    @template_library_all= YAML::load(File.open('./db/seeds/template_library.yml'))
end

In my view I did

reports.html.slim

javascript:
  var templateLibraryJSON = #{@template_library_all.to_json.html_safe};

So now I want to use the model to get the data from the database and parse it into JSON, instead of using a static file.

What I have done so far.

def query_library
@template_library_JSON = TemplateLibrary.all.map { |i| ['file_name:' , [i.file_name]]}
end

in my view

javascript:
  var templateJSON = #{@template_library_JSON.to_json.html_safe};

this returns me a JSON which looks like a JSON array.

[["file_name:", ["daily_data_count_report"]]]

Do I have to construct the JSON object ?

3
  • Can you try var templateJSON = #{j @template_library_JSON.to_json} (j is an alias for escape_javascript) ? And if not working, this: var templateJSON = #{j @template_library_JSON.as_json} (using as_json instead of to_json) Commented Sep 30, 2013 at 21:01
  • That didn't work, for some reason ruby adds escaping quotes and it breaks the view. But my concern was that I was not getting a valid JSON object which I can use in my JS Commented Sep 30, 2013 at 21:05
  • 1
    Hi, please edit your question and add en example of a JSON you want as an output, it is really not clear what you are trying to achieve. Do you want it to be [{"file_name": "daily_data_count_report"}]? Commented Sep 30, 2013 at 22:46

1 Answer 1

1

It looks like your #map call returns an array of arrays, not a hash. Try this instead:

@template_library_JSON = TemplateLibrary.all.map { |i| { :file_name => i.file_name } }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.