简体   繁体   中英

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 => :categorizations
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM