3

If I have a basic ruby on rails model set up (like for example the typical blogpost application) with an index action like:

def index
  @blogs=Blog.all
end

How do I convert all the blogs into a .json file? I know if I do:

def index
  @blogs=Blog.all
  respond_to do |format| 
  format.html{}
  format.json{render json: @blogs.to_json}
end

This will give a json output (what I want) but at the following path: /blogs.json in my browser, but I want an actual .json file (not just one being visible in browser at a path).

How would I go about doing this?

wpp
  • 7,093
  • 4
  • 33
  • 65
TABISH KHAN
  • 1,553
  • 1
  • 19
  • 32
  • Did you mean a json file to be downloaded? – sufinsha Jun 01 '15 at 04:09
  • if thats what it would take then yes. – TABISH KHAN Jun 01 '15 at 04:15
  • 1
    It's unclear what you're asking. Do you want the browser to prompt the user to download a `.json` file rather than displaying it? Or do you want to write the data to a `.json` file on the machine the server is running on? If the latter, do you just want to do it once, or have a command you can use to do it frequently? – Jordan Running Jun 01 '15 at 04:30
  • ActiveRecord seems to have had a to_json method that would serialize a model as json file, but it's since been deprecated. You may wish to look at http://www.rubydoc.info/github/rails/rails/ActiveSupport/JSON/Encoding/JSONGemEncoder – MarsAtomic Jun 01 '15 at 04:46
  • If all you want to do is return a json response from that url by default (not html) then just remove the `format.html{}` line or if you want to still be able to get an html version (at .html) set the default format in the routes file ala `resources :blogs, :defaults => { :format => :json }` – Camden Narzt Jun 01 '15 at 15:38

1 Answers1

0

Just replace

 format.json{render json: @blogs.to_json}

by

format.json{send_data @blogs.to_json}