Rails:获取属于模型的所有资产

时间:2013-04-05 01:18:16

标签: ruby-on-rails ruby-on-rails-3

我有一个拥有大量资产的品牌模型:

class Brand < ActiveRecord::Base
  attr_accessible :name, :logo1, :logo2, :colour1, :colour2, :prices_attributes

  has_attached_file :logo1
  has_attached_file :logo2

  has_many :users
  has_many :welcome_messages
  has_many :silos
  has_many :articles, :through => :silos
  has_many :libraries
  has_many :covers, :through => :libraries
  has_many :products
  has_many :prices, :through => :products, :autosave => true, :dependent => :destroy

  accepts_nested_attributes_for :prices

end

是否可以快速获得分配给每个品牌的所有资产?或者我必须为每个人做brand.articles.each do |article| ...这样的事情吗?

干杯!

2 个答案:

答案 0 :(得分:2)

如果您想加载所有关联,可以执行以下操作:

def self.all_associations
  includes(:users, :articles, :prices, :products) #and any other association
end

然后您可以投放Brand.all_associationsBrand.all_associations.find(1)

正如jvnill所写,这将导致n个数据库查询,所以在上面的例子中有5个数据库查询。

答案 1 :(得分:1)

除了mind.blank的解决方案,如果你不想重复自己,你可以进一步简化:

def self.all_associations
  includes *reflect_on_all_associations.collect(&:name)
end