gpt4 book ai didi

ruby-on-rails - as_json 没有在关联上调用 as_json

转载 作者:IT老高 更新时间:2023-10-28 12:48:16 25 4
gpt4 key购买 nike

我有一个模型,其中的数据在呈现为 json 时不应包含在内。所以我实现了类的 as_json 方法以使其行为适当。问题是当与此模型关联的其他模型呈现 json 时,我的自定义 as_json 没有被调用。

class Owner < ActiveRecord::Base
has_one :dog

def as_json(options={})
puts "Owner::as_json"
super(options)
end
end

class Dog < ActiveRecord::Base
belongs_to :owner

def as_json(options={})
puts "Dog::as_json"
options[:except] = :secret
super(options)
end
end

Loading development environment (Rails 3.0.3)
ruby-1.9.2-p136 :001 > d = Dog.first
=> #<Dog id: 1, owner_id: 1, name: "Scooby", secret: "I enjoy crapping everwhere">
ruby-1.9.2-p136 :002 > d.as_json
Dog::as_json
=> {"dog"=>{"id"=>1, "name"=>"Scooby", "owner_id"=>1}}
ruby-1.9.2-p136 :004 > d.owner.as_json(:include => :dog)
Owner::as_json
=> {"owner"=>{"id"=>1, "name"=>"Shaggy", :dog=>{"id"=>1, "name"=>"Scooby", "owner_id"=>1, "secret"=>"I enjoy crapping everwhere"}}}

感谢您的帮助

最佳答案

这是 known bug在 Rails 中。 (由于从以前的错误跟踪器迁移到 Github 问题,该问题被标记为已关闭,但在 Rails 3.1 中仍然存在问题。)

关于ruby-on-rails - as_json 没有在关联上调用 as_json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4840968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com