Cory Gagliardi
Cory Gagliardi

Reputation: 780

How do you render hashes as JSON in Rails 3

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

Upvotes: 4

Views: 13859

Answers (5)

mohakjuneja
mohakjuneja

Reputation: 161

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.

Upvotes: 1

Mutual Exception
Mutual Exception

Reputation: 1300

For those getting a NoMethodError, try this:

class AppController < ApplicationController
  respond_to :json

  ...
  def start
    app.start
    render json: { :ok => true }
  end
end

Upvotes: 0

Cory Gagliardi
Cory Gagliardi

Reputation: 780

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.

Upvotes: 0

Jonathan Lin
Jonathan Lin

Reputation: 20694

format.json { render json: { ok: true } } should work

Upvotes: 0

Josh Lindsey
Josh Lindsey

Reputation: 8803

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.

Upvotes: 7

Related Questions