这很难。
我有一个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
答案 0 :(得分:1)
您可以在parent
和Answer
上定义一个附加的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