Ruby on rails 模型的关联数组

Ruby on rails 模型的关联数组,ruby-on-rails,Ruby On Rails,有并没有办法为一个特定的模型创建一个关联数组 #app/models/users.rb class Users < ActiveRecord::Base has_many :things has_many :other_things @associations[ things, other_things ] 查看模型是否至少有一个关联。这将在我的应用程序中非常有用,并使抽象出我试图实现的许多行为成为可能。我不知道是否有一种优雅的方法可以做到这一点,但一种解决方案是创建一种方法,将您的

有并没有办法为一个特定的模型创建一个关联数组

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

has_many :things
has_many :other_things

@associations[ things, other_things ]

查看模型是否至少有一个关联。这将在我的应用程序中非常有用,并使抽象出我试图实现的许多行为成为可能。

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

def array_of_associations
  [things, other_things]
end
您的代码(如上所述)将工作:

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

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

您可以像添加两个数组一样添加两个关联

def all_things
  things + other_things
end
现在,当你调用所有的东西时,你有一个包含东西和其他东西的数组

但是,如果事物和其他事物是不同的模型,那么要小心

def all_things
  things + other_things
end