2010-05-27 79 views
4

我试图在我的一个模型中重写as_json,部分是为了包含来自另一个模型的数据,部分是为了去掉一些不必要的字段。从我读过这是Rails的3首选方法为了简单起见,假设我有这样的:覆盖as_json没有效果?

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

,并在我的控制器只需

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

然而,无论我尝试,输出始终包含完整的数据,这些字段不会被“:only”子句过滤。基本上,我重写似乎没有踢,但如果我把它改变,比方说......

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

...我真的不得到预期的JSON输出。我的语法错了吗?

+0

顺便说一句 - 我得到这个阅读后远http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/ – 2010-05-27 21:01:41

+0

参见http://stackoverflow.com/questions/2556468/override-as-json-or-to-json-model-class-name – 2010-05-28 02:48:41

+0

和https://rails.lighthouseapp.com/projects/8994/tickets/ 3087 – 2010-07-17 17:33:48

回答

0

一些进一步的测试,在控制器动作:

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

和模型:

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

输出:

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

然而,明确加入.to_json()来该类中的render语句以及在模型中重写to_json(而不是as_json)会生成期望的重新生成SULT。有了这个:

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

在我的控制器动作,和模型下的,倍率工作:

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

输出...

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

...这是预期产出。我发现了一个错误?我赢得奖品吗?

+0

你有没有定义自己的'to_json'或'as_json'的插件或其他东西? – x1a4 2010-05-28 02:47:52

+0

不是我所知道的,只有安装了Ward,Devise和CanCan的插件... – 2010-05-28 03:34:50