2, :resource_name=>"Vide-6ren">
gpt4 book ai didi

ruby-on-rails - 从多个 ActiveRecord 查询创建 Ruby 哈希的有效方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:46 30 4
gpt4 key购买 nike

我正在尝试以优雅的方式解决问题。

我有一个类:

class Pages < ActiveRecord::Base

# Relations
has_many :contents
has_many :videos
has_many :galleries
has_many :surveys
has_many :documents

end

我想创建这样的哈希

{"videos"=>{:resource_type=>"Video", :resource_id=>2, :resource_name=>"Video di prova"}, "documents"=>{}, "contents"=>{}, "surveys"=>{}, "galleries"=>{}}

收集我协会中的记录。

我写了一个方法

def get_page_resources
result = {}
['videos','galleries','documents','surveys','contents'].each do |r|
if self.try(r)
res_collection = {}
self.send(r).each do |resource|
res_collection.merge!(resource_type: resource.class.name)
res_collection.merge!(resource_id: resource.id)
res_collection.merge!(resource_name: resource.name)
end
result[r] = res_collection
end
end
return result
end

它有效,但我认为它很丑陋。有没有更好的方法来编写这个方法?

最佳答案

我会将您的代码重构为以下代码,我认为它具有可读性:

def resources
%w(videos galleries documents surveys contents).map do |name|
[
name, send(name).map do |resource|
{
resource_type: resource.class.name,
resource_id: resource.id,
resource_name: resource.name
}
end
]
end.to_h
end
  • get_ 开始一个方法不是惯用的Ruby。只需根据返回的内容命名该方法。 “page”也不需要在名称中,因为这是 Pages 上的一个方法。 (顺便说一下,ActiveRecord 模型通常以单数命名而不是复数命名。)
  • %w() 比常规的引用词数组好一点。
  • r 不是一个读者友好的变量名。我使用了 name,意思是“资源名称”,因为从上下文中可以明显看出它是资源的名称。
  • 创建可枚举的模式,通过迭代另一个可枚举来构建它,然后返回它,通常可以使用 mapeach_with_object 变得更清晰和更短。
  • 将数组转换为散列时,将其映射[key, value]对数组,然后将其转换为散列通常很方便.to_h.
  • try(r) 不执行任何操作,因为关联方法始终返回真值。我删除了它。
  • self. 在调用赋值方法以外的方法时不是必需的。
  • merge! 可以替换为散列文字。
  • return 在方法的末尾是不必要的,也不是惯用的。

重构很有趣,所以我按照说明回答了你的问题,但我同意 Nermin 的观点,你可能想研究一下序列化框架。

关于ruby-on-rails - 从多个 ActiveRecord 查询创建 Ruby 哈希的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35337731/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com