【问题标题】:Overriding as_json has no effect?覆盖 as_json 没有效果?
【发布时间】:2010-05-27 21:01:12
【问题描述】:

我试图在我的一个模型中覆盖 as_json,部分是为了包含来自另一个模型的数据,部分是为了去除一些不必要的字段。根据我的阅读,这是 Rails 3 中的首选方法。为了简单起见,假设我有类似的东西:

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 输出。我只是弄错了语法吗?

【问题讨论】:

标签: ruby-on-rails json model overriding


【解决方案1】:

这是一个bug,可惜没有奖品:

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

【讨论】:

    【解决方案2】:

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

    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() 显式添加到类中的渲染语句,并覆盖模型中的 to_json(而不是 as_json)会产生预期的结果。有了这个:

    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"}
        ]
    }
    

    ...这是预期的输出。我发现了一个错误吗?我中奖了吗?

    【讨论】:

    • 您是否安装了定义自己的to_jsonas_json 的插件或其他东西?
    猜你喜欢
    • 2011-12-02
    • 2012-11-15
    • 2020-03-28
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    相关资源
    最近更新 更多