gpt4 book ai didi

ruby-on-rails - 模型的关联数组

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

有什么方法可以为特定模型创建关联数组吗?

#app/models/users.rb
class Users < ActiveRecord::Base

has_many :things
has_many :other_things

@associations[ things, other_things ]

这样你就可以使用这样的东西:

#app/models/users.rb
@associations.select {|s| (s.count > 0)}

查看模型是否具有至少一种关联。这对我的应用程序非常有用,并且可以抽象出我尝试实现的许多行为。

最佳答案

我不知道是否有一种优雅的方法可以做到这一点,但一种解决方案是创建一种方法,将您的关联包装在一个数组中:

def array_of_associations
[things, other_things]
end

你的代码,如上,将工作:

model_instance.array_of_associations.select {|s| s.count > 0}

当然,这是在实例级别,但将其作为作用域或类方法提取到类级别应该不会太复杂。

关于ruby-on-rails - 模型的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704083/

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