4

has_many :throughRails/ActiveRecord でポリモーフィック アソシエーションをどのように熱心にロードしますか?

基本設定は次のとおりです。

class Post < ActiveRecord::Base
  has_many :categorizations, :as => :categorizable
  has_many :categories, :through => :categorizations
end

class Category < ActiveRecord::Base
  has_many :categorizations, :as => :category
  has_many :categorizables, :through => :categorizations
end

class Categorization < ActiveRecord::Base
  belongs_to :category, :polymorphic => true
  belongs_to :categorizable, :polymorphic => true
end

Rails 2.3.x と結​​合モデルでの二重ポリモーフィック アソシエーションのこのイーガー ロードの問題を解決したいと仮定すると、次の:throughようなものでアソシエーションをどのようにイーガー ロードしますか?

posts = Post.all(:include => {:categories => :categorizations})
post.categories # no SQL call because they were eager loaded

それはうまくいきません、何かアイデアはありますか?

4

1 に答える 1

0

これは、has_many :through を使用すると簡単に実現できます。ポリモーフィック アソシエーションを使用したい特定の理由はありますか?

has_many :through を使用すると、この ActiveRecord クエリを使用できます

posts = Post.all(:include => [:categorizations, :categories])
posts[0].categories      # no additional sql query
posts[0].categorizations # no additional sql query

モデル定義

class Post < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations
end

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :posts, :through => :categorizations
end

class Categorization < ActiveRecord::Base
  belongs_to :post
  belongs_to :category
end

これらの移行の使用

class CreatePosts < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.string :title
      t.timestamps
    end
  end

  def self.down
    drop_table :posts
  end
end

class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.string :name
      t.timestamps
    end
  end

  def self.down
    drop_table :categories
  end
end

class CreateCategorizations < ActiveRecord::Migration
  def self.up
    create_table :categorizations do |t|
      t.integer :post_id
      t.integer :category_id
      t.timestamps
    end
  end

  def self.down
    drop_table :categorizations
  end
end
于 2010-09-21T04:22:16.263 に答える