1

モデルレベルで熱心にロードできるかどうか疑問に思います:

# country.rb
class Country < ActiveRecord::Base
  has_many :country_days

  def country_highlights
    country_days.map { |country_day| country_day.shops }.flatten.uniq.map { |shop| shop.name }.join(", ")
  end
end

# country_day.rb
class CountryDay < ActiveRecord::Base
  belongs_to :country
  has_many :country_day_shops
  has_many :shops, :through => :country_day_shops
end

# shop.rb
class Shop < ActiveRecord::Base    
end

.includesほとんどの場合、ポリモーフィックな関連付けのため、コントローラーで使用するのは困難です。コントローラーcountry_highlightsに追加する必要がないように、モデルレベルでメソッドを熱心にロードする方法はありますか?.includes

4

2 に答える 2

2

モデル インスタンスから country_days を「イーガー ロード」することはできませんが、has_many through:. 追加マップもスキップできます。

# country.rb
class Country < ActiveRecord::Base
  has_many :country_days
  has_many :country_day_shops, through: :country_days  #EDIT: You may have to add this relationship
  has_many :shops, through: :country_day_shops #And change this one to use the new relationship above.

  def country_highlights
    shops.distinct_names.join(", ")
  end
end

# country_day.rb
class CountryDay < ActiveRecord::Base
  belongs_to :country
  has_many :country_day_shops
  has_many :shops, :through => :country_day_shops
end

# shop.rb
class Shop < ActiveRecord::Base
  def self.distinct_names
    pluck("DISTINCT shops.name")  #Edit 2: You may need this instead of 'DISTINCT name' if you get an ambiguous column name error.
  end
end

は、すべての country_day レコードをロードしてから、country_day レコードごとに関連付けられたショップをロードするのではなくhas_many through:、 a を使用しJOINて関連ショップ レコードをロードします。

pluck("DISTINCT name")は、DB を使用して を実行し、DB 内のショップのすべての一意の名前の配列を返しますSELECT DISTINCT。そのため、重複したレコードは返されず、pluck必要なのが文字列だけの場合でも、ActiveRecord インスタンスのロードが回避されますname

于 2013-04-21T19:23:49.077 に答える