2010-09-20 76 views
4

你如何在Rails/ActiveRecord中加載多態的has_many :through關聯?Eager Load Polymorphic has_many:通過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 

這不工作,有什麼想法?

回答

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 
+0

這個例子並不多態。 – cicloon 2013-06-12 11:56:55