检索 AR 模型的所有关联属性?

2024-04-21

您认为检索 AR 模型所有关联的所有属性的最佳方法是什么?

即:假设我们有模型Target.

class Target < ActiveRecord::Base
  has_many :countries
  has_many :cities
  has_many :towns
  has_many :colleges
  has_many :tags

  accepts_nested_attributes_for :countries, :cities, ...
end

我想通过调用 Target 实例上的方法来检索所有关联的属性:

target.associations_attributes
>> { :countries => { "1" => { :name => "United States", :code => "US", :id => 1 }, 
                     "2" => { :name => "Canada", :code => "CA", :id => 2 } },
     :cities => { "1" => { :name => "New York", :region_id => 1, :id => 1 } },
     :regions => { ... },
     :colleges => { ... }, ....
   }

目前,我通过迭代每个关联,然后迭代关联的每个模型来完成这项工作,但这有点昂贵,您认为我可以如何优化它?

请注意:我意识到你不能打电话target.countries_attributes on has_many与 的关联nested_attributes, one_to_one协会允许打电话target.country_attributes


我不清楚你所说的迭代所有关联是什么意思。您已经在使用反射了吗?

仍然好奇是否有更简洁的方法,但这就是我能想到的,这或多或少会导致您在示例中显示的哈希值:

class Target < ActiveRecord::Base
  has_many :tags

  def associations_attributes
    # Get a list of symbols of the association names in this class
    association_names = self.class.reflect_on_all_associations.collect { |r| r.name }
    # Fetch myself again, but include all associations
    me = self.class.find self.id, :include => association_names
    # Collect an array of pairs, which we can use to build the hash we want
    pairs = association_names.collect do |association_name|
      # Get the association object(s)
      object_or_array = me.send(association_name)
      # Build the single pair for this association
      if object_or_array.is_a? Array
        # If this is a has_many or the like, use the same array-of-pairs trick
        # to build a hash of "id => attributes"
        association_pairs = object_or_array.collect { |o| [o.id, o.attributes] }
        [association_name, Hash[*association_pairs.flatten(1)]]
      else
        # has_one, belongs_to, etc.
        [association_name, object_or_array.attributes]
      end
    end
    # Build the final hash
    Hash[*pairs.flatten(1)]
  end
end

这是一个 IRB 会议script/console展示它是如何工作的。首先,一些环境:

>> t = Target.create! :name => 'foobar'
=> #<Target id: 1, name: "foobar">
>> t.tags.create! :name => 'blueish'
=> #<Tag id: 1, name: "blueish", target_id: 1>
>> t.tags.create! :name => 'friendly'
=> #<Tag id: 2, name: "friendly", target_id: 1>
>> t.tags
=> [#<Tag id: 1, name: "blueish", target_id: 1>, #<Tag id: 2, name: "friendly", target_id: 1>]

这是新方法的输出:

>> t.associations_attributes
=> {:tags=>{1=>{"id"=>1, "name"=>"blueish", "target_id"=>1}, 2=>{"id"=>2, "name"=>"friendly", "target_id"=>1}}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检索 AR 模型的所有关联属性? 的相关文章

随机推荐

  • 如何为 2 个不同的视图重用一个控制器?

    我定义了一个控制器 并将其应用于两个有细微差别的视图 角度代码 app controller MyCtrl function scope scope canSave false scope demo files filename aaa h
  • 无法在 Istio 代理后面的 k8s 中建立与 VerneMQ 集群的 mqtt 连接

    我正在设置 k8s 本地 k8s 集群 对于测试 我在使用 kubeadm 设置的虚拟机上使用单节点集群 我的要求包括在 k8s 中运行 MQTT 集群 vernemq 并通过 Ingress istio 进行外部访问 无需部署 ingre
  • @GenerateValue with Strategy=GenerationType.AUTO 重启后生成重复值

    我有一个 ID 配置为的休眠实体 Id GeneratedValue strategy GenerationType AUTO private Long id 新元素的创建在第一次运行时工作正常 但是 如果我重新启动应用程序并检索记录 下次
  • 如何配置 prometheus-operator 从 Kubernetes 上的 cAdvisor 收集?

    我在用普罗米修斯操作员 https github com coreos prometheus operator管理一个普罗米修斯 https prometheus io 部署在我的库伯内斯 https kubernetes io 簇 该设置
  • VSTO - 存储 Excel 工作簿设置的最佳位置

    我有一个用 VBA 实现的旧版 Excel AddIn 我正在使用 VSTO 慢慢将其移植到 net 使用此插件 我将每个工作簿的设置存储在隐藏工作表中 我想知道是否有更好的方法使用 VSTO 来做到这一点 您可以使用自定义文档属性 htt
  • 解析器中的运算符优先级和结合性 (Haskell)

    我正在尝试扩展递归下降解析器来处理新运算符并使它们正确关联 最初只有四个运算符 并且它们都具有相同的优先级 我正在查看的函数是 parseExpRec 函数 parseExpRec Exp gt Token gt Exp Token par
  • MySQL - 选择最近 10 位作者的最新帖子

    我有一个包含许多不同作者的博客文章的表 我想做的是显示 10 位最新作者各自的最新帖子 每个作者的帖子只是按顺序添加到表中 这意味着单个作者可能会发布多篇帖子 我花了很多时间想出一个查询来做到这一点 这给了我最后 10 个唯一的作者 ID
  • 使用 Gradle,如何打印每个任务执行所需的时间?

    现在 对于频繁运行的 gradle 目标之一 输出如下所示 DataPlanner clean common clean server clean simulator clean util clean util compileJava ut
  • 美丽汤无法“获取”完整网页

    我正在使用 BeautifulSoup 来解析来自的一堆链接但它并没有提取我想要的所有链接 为了尝试找出原因 我将 html 下载到 web page html 并运行 soup BeautifulSoup open web page ht
  • 在 Flash AS3 中捕获未处理的 IOErrorEvent

    错误 2044 未处理的 IOErrorEvent text 错误 2036 从不加载 完全的 这就是我每次尝试使用加载器加载不存在的图像时看到的情况 我正在获取 URL 列表 但无法验证它们是否指向任何有用的内容 每当遇到 404 时 它
  • URL 重写破坏了 CSS 链接

    我使用以下设置进行网址重写 RewriteEngine On RewriteCond REQUEST FILENAME d RewriteCond REQUEST FILENAME f RewriteRule index php url 1
  • October CMS:如何扩展后端用户的角色范围

    我已经能够延长Backend Models User类并添加一个范围查询方法以仅检索超级用户 public function boot User extend function model model gt addDynamicMethod
  • 如何自动链接本地npm包?

    我正在构建两个相互依赖的私有 npm 包 说我有 project my commons package json name my commons version 0 0 1 my server package json dependenci
  • Beaglebone Black 上的 GPIO

    我目前遇到了 Beaglebone black GPIO 引脚的问题 我正在寻找一种正确的方法来读取 C 中的 GPIO 引脚 p8 4 的值 如果我理解正确的话 我尝试使用一个库 该库使用了在引入设备树之前不支持的旧方法 我尝试寻找其他解
  • 如果方法只需要 ajax 调用,会返回什么错误?

    如果操作期望仅通过 AJAX 使用 但在没有正确的 ajax 标头的情况下调用 则操作应返回什么 HTTP 状态 我觉得我应该指出一些错误 但我真的找不到合适的错误 我想最好是 405 Method not allowed 但是如果例如 a
  • PowerShell 中的“net use”不指定驱动器

    通过 net use 您可以执行以下操作 net use server user domian username 然后 它会提示输入密码 并且使用任何程序 cmd Explorer Word 等 与该服务器建立的任何进一步 CIFS 连接都
  • 验证 TextBox 中的文本更改

    我已经在 WinForm 中的文本框上实现了验证规则 并且效果很好 但是 只有当我跳出该字段时 它才会检查验证 我希望它在框中输入任何内容以及每次内容发生变化时立即进行检查 我还希望它在 WinForm 打开后立即检查验证 我记得最近通过设
  • 一页上有多个夏季笔记 div

    我正在尝试获取特定夏季笔记 div 的代码 其中单个页面上有多个笔记 div 我的暑假笔记是用 php 从数据库创建的 如下所示 div class tab content div class tab pane div class summ
  • 如何在大窗口上优化窗口聚合?

    我在 Spark 2 4 4 中使用带有大窗口的窗口函数 例如 Window partitionBy id orderBy timestamp 在我的测试中 我有大约 70 个不同的 ID 但我可能有大约 200 000 行 ID 如果没有
  • 检索 AR 模型的所有关联属性?

    您认为检索 AR 模型所有关联的所有属性的最佳方法是什么 即 假设我们有模型Target class Target lt ActiveRecord Base has many countries has many cities has ma