我有一个
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
,但事实并非如此。为什么不呢?我怎么能这样做呢?
由于
答案 0 :(得分:0)
您可以使用only
来限制对Company
模型中includes
内关联的User
属性的访问权限,如下所示:
class User
def as_json(options = {})
opts = {
only: [:id, :name],
includes: {company: {only: [:id, :name]}}
}.merge(options)
super(opts)
end
end