#as_json includes不会在assoc上调用as_json

时间:2016-11-14 09:56:31

标签: ruby-on-rails ruby

我有一个

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,但事实并非如此。为什么不呢?我怎么能这样做呢?

由于

1 个答案:

答案 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