【问题标题】:Retrieving deeply nested ActiveRecord associations检索深度嵌套的 ActiveRecord 关联
【发布时间】:2015-06-30 21:45:26
【问题描述】:

我无法弄清楚如何检索具有深度嵌套关联的 ActiveRecord 对象。下面是我试图以 JSON 对象表示的示例。

目前,我的项目模型有:

  1. has_many :groups
  2. has_many :users, through: :groups
  3. has_many :members, through: :groups, source: :users

预期结果(JSON):

{
  "id": 7,
  "name": "Test Project",
  "description": "Project description",
  "groups": [
    {
      "id": 1,
      "name": "Test Group 1",
      "description": "First test group",
      "members": [
        {
          "id": 1,
          "name": "Admin",
          "email": "admin@exmaple.com"
        },
        {
          "id": 2,
          "name": "Test User",
          "email": "test@exmaple.com"
        }
      ]
    }
  ]
}

示例代码:

class Project < ActiveRecord::Base
  has_many :groups
  has_many :users, through: :groups
  has_many :members, through: :groups, source: :users
end

我最接近预期结果的方法是在项目模型中添加一个组方法来获取所有成员:

最近的结果(JSON):

{
  "id": 7,
  "name": "Test Project",
  "description": "Project description",
  "groups": [
    {
      "id": 1,
      "name": "Admin",
      "email": "admin@exmaple.com"
    },
    {
      "id": 2,
      "name": "Test User",
      "email": "test@exmaple.com"
    }
  ]
}

示例代码:

class Project < ActiveRecord::Base
  has_many :groups
  has_many :users, through: :groups
  has_many :members, through: :groups, source: :users

  def groups
    members.all
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations model-associations


    【解决方案1】:

    您可以尝试使用 activemodel 序列化程序来包含相关记录。

    class ProjectSerializer < ActiveModel::Serializer
      attributes :id
      has_many :groups 
    end
    
    class GroupSerializer < ActiveModel::Serializer
      attributes :id
      has_many :members
    end
    

    您可以查看:https://github.com/rails-api/active_model_serializers

    has_many、has_one 和belongs_to 声明描述了资源之间的关系。默认情况下,当你序列化一个帖子时,你也会得到它的评论。

    【讨论】:

    • 这太完美了!谢谢。我们一直在使用序列化程序,但我认为我没有完全理解它们。我的意思是,我仍然不知道,但在这种情况下,你肯定帮助我理解了它们。谢谢!
    • 不客气。我认为您可以从阅读什么是序列化开始:en.wikipedia.org/wiki/Serialization > 在计算机科学中,在数据存储的上下文中,序列化是将数据结构或对象状态转换为可以存储的格式的过程(例如,在文件或内存缓冲区,或通过网络连接链接传输)并稍后在相同或另一个计算机环境中重建。
    【解决方案2】:

    你可以这样做:

    class Project < ActiveRecord::Base
      has_many :groups
      has_many :users, through: :groups
      has_many :members, through: :groups, source: :users
    end
    
    Project.find(7).to_json(include: {groups: {include: :users}})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多