Overriding as_json has no effect?

家住魔仙堡 提交于 2019-12-05 17:39:23

Some further testing, in the controller action:

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 overriding to_json in the model (instead of as_json) produces the expected result. With this:

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

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

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

Outputs...

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

...which is the expected output. Have I found a bug? Do I win a prize?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!