How to convert Ruby on Rails Model to a .json file?

1.5k Views Asked by At

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?

1

There are 1 best solutions below

0
On

Just replace

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

by

format.json{send_data @blogs.to_json}