【问题标题】:polymorphic and one-to-many association多态和一对多关联
【发布时间】:2013-04-25 18:47:59
【问题描述】:

我有一个协作模型,它与 Grade | 具有多态关联。学校,以及与用户的一对多关联

  belongs_to :owner, polymorphic: true
  belongs_to :user, foreign_key: "teacher_id"

这是我管理可以访问学校或年级的用户的方式。现在,我需要做这样的事情

School.first.teachers 
Grade.first.teachers

我认为在年级/学校模型中应该是这样的

has_many :teachers, through: :collaborations, foreign_key: "teacher_id" 

但这似乎不是正确的解决方案。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord associations


    【解决方案1】:
    has_many :collaborations, :as => :owner
    has_many :teachers, :through => :collaborations, :source => :user
    

    【讨论】:

      【解决方案2】:

      您需要建立与协作的多态关联。试试:

      class School < ActiveRecord::Base
        has_many :collaborations, :as => :owner
        has_many :teachers, :through => :collaborations
      end
      

      【讨论】:

      • 就像 Babur Usenakunov 在上一篇文章中所说,我也需要 source: :user 。 :) 感谢您的回答
      猜你喜欢
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 2021-10-07
      • 1970-01-01
      相关资源
      最近更新 更多