开发者

Eager Load Polymorphic has_many :through Associations in ActiveRecord?

How do you eager load polymorphic has_many :through associations in Rails/ActiveRecord?

Here's the base setup:

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 => :categori开发者_如何学Pythonzations
end

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

Assuming that we want to solve this eager loading problem for Rails 2.3.x and double polymorphic associations on the join model, how do you eager load the :through association on something like this:

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

That's not working, any ideas?


This is easier to accomplish with has_many :through. Do you have a specific reason for wanting to use polymorphic associations?

With has_many :through you can use this ActiveRecord query

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

Model definitions

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

Using these migrations

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜