你如何急切加载多态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 的这个急切加载问题,以及 join 模型上的双多态关联,你如何急切加载
:through
像这样的关联:posts = Post.all(:include => {:categories => :categorizations})
post.categories # no SQL call because they were eager loaded
这是行不通的,有什么想法吗?
最佳答案
使用 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
关于ruby-on-rails - Eager Load Polymorphic has_many :through Associations in ActiveRecord?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3753903/