Rails 5.2渴望加载多态嵌套

时间:2019-02-20 00:17:39

标签: ruby-on-rails activerecord

是否可能渴望加载多态嵌套关联?我怎么能include doctor_profile Recommendationpatient_profile Post的{​​{1}}?

我可以致电Activity.includes(:trackable).last(10),但不确定如何包括过去的关联模型。我尝试过belongs_to :recommendation, -> { includes :patient_profile, :doctor_profile}并没有运气

class Activity
  belongs_to :trackable, polymorphic: true

end

class Recommendation
  has_many :activities, as: :trackable
  belongs_to :doctor_profile

end

class Post
  has_many :activities, as: :trackable
  belongs_to :patient_profile

end

3 个答案:

答案 0 :(得分:1)

参考this SO answer and comments 对于您的问题,您可以使用多态表中的foreign_type字段进行管理,以引用使用该模型的模型

class Activity
  belongs_to :trackable, polymorphic: true
  # below is additional info
  belongs_to :recommendation, foreign_type: 'Recommendation', foreign_key: 'trackable_id'
  belongs_to :post, foreign_type: 'Post', foreign_key: 'trackable_id'
end

您可以称之为

Activity.includes(recommendation: :doctor_profile).last(10)
Activity.includes(post: :patient_profile).last(10)

Activity.includes(推荐::doctor_profile)表示

  • 活动将通过foreign_type和trackable_id加入推荐
  • 然后根据推荐,将doctor_profile与doctor_profile_id一起加入

答案 1 :(得分:0)

以上答案有效,但实际上foreign_type的使用并不能满足评论者的意图。

https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

foreign_type用于为确定关系的类类型的列指定名称。

我认为这里的预期结果是改为使用class_name来指定该关系所引用的表。如果该关系与表具有相同的名称,则实际上可以推断出class_name(这就是为什么提供的答案首先起作用的原因)

答案 2 :(得分:0)

为了使上述答案起作用,为 inverse_of 指定 belongs_to 并为 has_many 关联添加使一切正常。例如:

class Activity
  belongs_to :trackable, polymorphic: true
  # below is additional info
  belongs_to :recommendation, foreign_type: 'Recommendation', foreign_key: 'trackable_id', inverse_of: :activities
  belongs_to :post, foreign_type: 'Post', foreign_key: 'trackable_id', inverse_of: :activities
end

Post 模型上:

has_many :activities, inverse_of: :post 

Recommendation 模型上:

has_many :activities, inverse_of: :recommendation 
相关问题