Rails JSON Injection

In Rails 2.3, I always used

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

send JSON data to my interface. In Rails 3 I use

 respond_to :json ... respond_with @foobar 

But what I miss: I need the value "success" in the JSON structure. What is the correct way to insert such data into a JSON response in Rails 3?


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

 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 } 
+6
json ruby-on-rails
source share
2 answers

When things are not suitable by default, you need to go back to the previous configured path. respond_with accepts the block.

 respond_with @foobar do |format| format.json { render :json => { :success => true, :data => @foobar} } end 
+4
source share

You cannot use an object as a value. You just add the key / value inside with an overriding serializable_hash method

But you can create your hash in response_with

 respond_with { :success => true, :data => @foobar} 
+1
source share

All Articles