gpt4 book ai didi

ruby-on-rails - rails : can I use two nested map?

转载 作者:行者123 更新时间:2023-12-05 04:12:04 25 4
gpt4 key购买 nike

  def has_name? name
results = auths.map do |auth|
auth.role_groups.map do |role_group|
role_group.resources.any?{ |r| r.name == name}
end
end
results.any?
end

这是User模型中的一个方法
1 个用户有多个授权
1 个 auth 有多个 role_groups
1 role_group 有很多资源

我在那里使用了两个 map ,但它没有返回我期望的结果。这是我第一次使用两个嵌套的 map ,我可以这样使用吗?

最佳答案

你可以,但结果将包含一个数组的数组并且它不被认为是空的。

[[]].any?
=> true

#flat_map 在这里可能对您有帮助

def has_name? name
results = auths.flat_map do |auth|
auth.role_groups.map do |role_group|
role_group.resources.any?{ |r| r.name == name}
end
end

results.any?
end

或者您可以将您的解决方案完全更改为使用 sql 的更高性能的解决方案(没有看到您的模型,不确定它是否有效)

auths.joins(role_groups: :resources).where(resources: { name: name }).exists?

关于ruby-on-rails - rails : can I use two nested map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41258678/

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