How do you render hashes as JSON in Rails 3

12,982

Solution 1

This was very close. However, it does not automatically convert the hash to json. This was the final result:

class AppControlls < ApplicationController
  respond_to :json

  def start
    app.start
    respond_with( { :ok => true }.to_json )
  end
end

Thanks for the help.

Solution 2

When you specify a respond_to, then in your actions you would make a matching respond_with:

class AppControlls < ApplicationController
  respond_to :json

  def index
    hash = { :ok => true }
    respond_with(hash)
  end
end

It looks like you're conflating the old respond_to do |format| style blocks with the new respond_to, respond_with syntax. This edgerails.info post explains it nicely.

Solution 3

class AppController < ApplicationController

respond_to :json

def index
  hash = { :ok => true }
  respond_with(hash.as_json)
end

end

You should never use to_json to create a representation, only to consume the representation.

Share:
12,982
Cory Gagliardi
Author by

Cory Gagliardi

Updated on June 04, 2022

Comments

  • Cory Gagliardi
    Cory Gagliardi almost 2 years

    I found how to render ActiveRecord objects in Rails 3, however I cannot figure out how to render any custom objects. I am writing an app without ActiveRecord. I tried doing something like this:

    class AppController < ApplicationController
      respond_to :json
    
      ...
      def start
        app.start
        format.json { render :json => {'ok'=>true} }
      end
    end