Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails JSON injection

In Rails 2.3 I always used

render :json => { :success => true, :data => @foobar}

to send JSON data to my frontend. In Rails 3 I'm using

respond_to :json
...
respond_with @foobar

But what I'm missing: I need the 'success' value within the JSON structure. What's the right way to inject such data into JSON response in Rails 3?


Hm, tried this too, but I get the following error as result:

SyntaxError (app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting '}'
respond_with { :success => true, :data => @property }
                          ^
/app/controllers/properties_controller.rb:13: Can't assign to true
respond_with { :success => true, :data => @property }
                                ^
app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
respond_with { :success => true, :data => @property }
like image 635
ctp Avatar asked Oct 21 '10 07:10

ctp


2 Answers

When things doesn't fit the default, you need to go back to the previous customized way. respond_with accepts a block.

respond_with @foobar do |format|
  format.json { render :json => { :success => true, :data => @foobar} }
end
like image 168
Simone Carletti Avatar answered Nov 15 '22 07:11

Simone Carletti


You can't use the object like value. You just add some key/value inside with override serializable_hash method

But you can generate your hash in respond_with

respond_with { :success => true, :data => @foobar}
like image 36
shingara Avatar answered Nov 15 '22 08:11

shingara