0

多くのアセットを持つ Brand モデルがあります。

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| ...か?

乾杯!

4

2 に答える 2

2

すべての関連付けを熱心に読み込みたい場合は、次のようにします。

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

次に、実行するBrand.all_associationsか、Brand.all_associations.find(1)

jvnill が書いたように、これにより n データベース クエリが発生するため、上記の例では 5 つのデータベース クエリになります。

于 2013-04-05T01:22:40.963 に答える
1

mind.blank のソリューションに加えて、繰り返したくない場合は、さらに一歩単純化できます。

def self.all_associations
  includes *reflect_on_all_associations.collect(&:name)
end
于 2013-04-05T05:11:30.220 に答える