【问题标题】:Rails 5.2 eager load polymorphic nestedRails 5.2 急切加载多态嵌套
【发布时间】:2019-07-13 14:03:43
【问题描述】:

是否可以预先加载多态嵌套关联?我怎样才能 include doctor_profile's 为 Recommendation's 和 patient_profile's 为 Post's?

我可以致电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

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    为了使上述答案起作用,为belongs_to 指定inverse_of 并为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 
    

    【讨论】:

      【解决方案2】:

      上述答案有效,但 foreign_type 的使用实际上并不应该达到评论者的意图。

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

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

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

      【讨论】:

        【解决方案3】:

        参考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(recommendation: :doctor_profile) 表示

        • Activity 将使用 foreign_type 和 trackable_id 加入推荐
        • 然后从推荐中加入 doctor_profile 和 doctor_profile_id

        【讨论】:

        • 谢谢。是否可以在 1 次通话中进行包含?
        • 你可以先试试,我编辑了我的答案,添加了一些关于一次通话中包含的解释
        • 你可以。谢谢 - Activity.includes(recommendation: :doctor_profile, post: :patient_profile).last(10)
        猜你喜欢
        • 2013-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        • 1970-01-01
        • 2013-04-13
        相关资源
        最近更新 更多