Eager Load Polymorphic has_many:通过ActiveRecord中的关联?

时间:2010-09-20 17:33:54

标签: ruby-on-rails activerecord polymorphic-associations

如何在Rails / ActiveRecord中加载多态has_many :through关联?

以下是基本设置:

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

那不行,有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用has_many:through更容易实现。您是否有特定原因想要使用多态关联?

使用has_many:通过您可以使用此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