【发布时间】:2011-06-17 23:29:05
【问题描述】:
我有一个模型,其数据在呈现为 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
加载开发环境(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
狗::as_json
=> {"dog"=>{"id"=>1, "name"=>"Scooby", "owner_id"=>1}}
ruby-1.9.2-p136 :004 > d.owner.as_json(:include => :dog)
所有者::as_json
=> {"owner"=>{"id"=>1, "name"=>"Shaggy", :dog=>{"id"=>1, "name"=>"Scooby", "owner_id"= >1, "secret"=>"我喜欢到处拉屎"}}}
感谢您的帮助
【问题讨论】:
-
我也有这个问题,在 Rails 3.0.9 上使用 Mongoid。
标签: ruby-on-rails json ruby-on-rails-3