Overriding as_json has no effect?

I am trying to override as_json in one of my models, partly to include data from another model, partly to highlight unnecessary fields. From what I read, this is the preferred approach in Rails 3. To make it simple, let's say I have something like:

class Country < ActiveRecord::Base def as_json(options={}) super( :only => [:id,:name] ) end end 

and in my controller just

 def show respond_to do |format| format.json { render :json => @country } end end 

However, no matter what I try to do, the output always contains complete data, fields are not filtered by the condition:: only. In principle, my redefinition does not seem to work, although if I change it, I will say ...

 class Country < ActiveRecord::Base def as_json(options={}) {foo: "bar"} end end 

... I really get the expected JSON output. Did I just get the syntax wrong?

+4
source share
2 answers

This is a mistake, but alas there is no prize:

https://rails.lighthouseapp.com/projects/8994/tickets/3087

+2
source

Some additional testing in the action of the controller:

 format.json { render :json => @country } 

And in the model:

 class Country < ActiveRecord::Base has_many :languages def as_json(options={}) super( :include => [:languages], :except => [:created_at, :updated_at] ) end end 

Outputs:

 { created_at: "2010-05-27T17:54:00Z" id: 123 name: "Uzbekistan" updated_at: "2010-05-27T17:54:00Z" } 

However, explicitly adding .to_json () to the render statement in the class, and the primary to_json in the model (instead of as_json) gives the expected result. Wherein:

 format.json { render :json => @country.to_json() } 

in my controller action, and below the override in the model works:

 class Country < ActiveRecord::Base has_many :languages def to_json(options={}) super( :include => [:languages], :except => [:created_at, :updated_at] ) end end 

Outlets ...

 { id: 123, name: "Uzbekistan", languages: [ {id: 1, name: "Swedish"}, {id: 2, name: "Swahili"} ] } 

... which is the expected exit. Did I find a mistake? Did I win a prize?

0
source

Source: https://habr.com/ru/post/1311143/


All Articles