我有一个#as_json包括不叫as_json在assoc命令
User(id, name, something_secret, created_at, updated_at)
和
Company(id, name, something_secret, created_at, updated_at)
型号:
class Company
def as_json(options = {})
opts = {
only: [:id, :name]
}.merge(options)
super(opts)
end
end
class User
def as_json(options = {})
opts = {
only: [:id, :name],
includes: [:company]
}.merge(options)
super(opts)
end
end
如果我打电话company.as_json
,那么一切都很好,我得到:
{
id: 1,
name: "Name"
}
但是,如果我叫user.as_json
,那么它包括所有的公司的东西
{
id: 1,
name: "Jim",
company: {
id: 1,
name: "Name",
something_secret: "super secret",
created_at: "2016-11-12 13:03:07",
updated_at: "2016-11-12 13:03:07"
}
}
这似乎应该呼吁公司#as_json
,但事实并非如此。为什么不呢?我怎样才能做到这一点?
感谢
我同意,现在看来似乎应该是递归的,因为'to_json'是递归调用,但它被认为是不好的形式来调用或重写此方法。如果你发现自己经常这样做,我会看看演示者。 ['draper'](https://github.com/drapergem/draper)gem使其变得简单,并且表现形式非常模块化 – engineersmnky