Rails:范围内与trackable_type的热切负载关联

时间:2019-01-24 03:47:11

标签: ruby-on-rails scope associations eager-loading

这很难。

我有一个col1, col2, col3, col4 1,'my friend's pet is a dog','Husky',True 模型:

Activity

所以,如果我这样做:

class Activity < ActiveRecord::Base
    belongs_to :trackable, polymorphic: true
    scope :include_all, -> { includes(:trackable) }
    ...
end

上面的代码运行良好,但是如果我也想加载可跟踪记录的父级怎么办?那些模型也有不同的父母:

@activities = Activity.include_all 模型:

Answer

class Answer < ActiveRecord::Base belongs_to :question has_many :activities, as: :trackable scope :include_all, -> { includes(:question) } ... end 模型:

Post

class Post < ActiveRecord::Base belongs_to :blog has_many :activities, as: :trackable scope :include_all, -> { includes(:blog) } ... end 模型:

Category

请注意,每个模型中的class Category < ActiveRecord::Base has_many :activities, as: :trackable scope :include_all, -> {} ... end 范围显示要包含的关联。我尝试过

include_all

当带有class Activity < ActiveRecord::Base ... scope :include_all, -> { includes(trackable: :question) } ... end = Activity的{​​{1}}出现时,这将中断。

有什么想法吗?


Rick的回答是一个很好的方法,但是,有没有办法在另一个范围内使用关联范围?对于没有像trackable_type这样的父母的协会来说,这非常方便。

类似

Post

2 个答案:

答案 0 :(得分:1)

您可以在parentAnswer上定义一个附加的Post关联,以扩展trackable ducktype的接口:

class Answer < ActiveRecord::Base
  belongs_to :question
  belongs_to :parent, class_name: :Question, foreign_key: :question_id
  ...
end
class Post < ActiveRecord::Base
  belongs_to :blog
  belongs_to :parent, class_name: :Blog, foreign_key: :blog_id
  ...
end
class Activity < ActiveRecord::Base
  scope :include_all, -> { includes(trackable: :parent) }
  ...
end

答案 1 :(得分:1)

钉了!如果将范围直接添加到belongs_to行,则关联将加载该范围。

class Activity < ActiveRecord::Base
    belongs_to :trackable, -> { include_all } , polymorphic: true
    ...
end