[英]Eager Load Polymorphic has_many :through Associations in ActiveRecord?
How do you eager load polymorphic has_many :through
associations in Rails/ActiveRecord? 你如何渴望加载多态
has_many :through
Rails / ActiveRecord中的关联?
Here's the base setup: 这是基本设置:
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
Assuming that we want to solve this eager loading problem for Rails 2.3.x and double polymorphic associations on the join model, how do you eager load the :through
association on something like this: 假设我们想要解决Rails 2.3.x的这个急切加载问题以及连接模型上的双重多态关联,你如何急切地加载
:through
关联这样的事情:
posts = Post.all(:include => {:categories => :categorizations})
post.categories # no SQL call because they were eager loaded
That's not working, any ideas? 这不起作用,任何想法?
This is easier to accomplish with has_many :through. 使用has_many:through更容易实现。 Do you have a specific reason for wanting to use polymorphic associations?
您是否有特定原因想要使用多态关联?
With has_many :through you can use this ActiveRecord query 使用has_many:通过您可以使用此ActiveRecord查询
posts = Post.all(:include => [:categorizations, :categories])
posts[0].categories # no additional sql query
posts[0].categorizations # no additional sql query
Model definitions 模型定义
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
Using these migrations 使用这些迁移
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.