Overriding as_json has no effect?

2019-05-07 23:10发布

I'm trying to override as_json in one of my models, partly to include data from another model, partly to strip out some unnecessary fields. From what I've read this is the preferred approach in Rails 3. To keep it simple, let's say I've got something like:

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

and in my controller simply

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

Yet whatever i try, the output always contains the full data, the fields are not filtered by the ":only" clause. Basically, my override doesn't seem to kick in, though if I change it to, say...

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

...I do indeed get the expected JSON output. Have I simply got the syntax wrong?

2条回答
我命由我不由天
2楼-- · 2019-05-08 00:07

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?

查看更多
做个烂人
3楼-- · 2019-05-08 00:08
登录 后发表回答