4

您如何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

假设我们要解决 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 回答