热切加载多态 has_many:通过 ActiveRecord 中的关联?

Lan*_*ard 5 activerecord ruby-on-rails polymorphic-associations

如何has_many :through在 Rails/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
Run Code Online (Sandbox Code Playgroud)

假设我们想要解决 Rails 2.3.x 的急切加载问题以及连接模型上的双重多态关联,那么如何急切加载:through这样的关联:

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

这不起作用,有什么想法吗?

mar*_*lly -1

使用 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
Run Code Online (Sandbox Code Playgroud)

模型定义

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
Run Code Online (Sandbox Code Playgroud)

使用这些迁移

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
Run Code Online (Sandbox Code Playgroud)