Rails多态连接表工作两种方式

时间:2016-04-03 08:58:18

标签: ruby-on-rails activerecord

我开始学习更高级的关联,并且多态连接表看起来非常有趣,但我已经遇到了一个不好的限制。

我的模特:

school_class.rb:

class SchoolClass < ActiveRecord::Base
  has_many :class_of_schools, as: :school_model, dependent: :destroy
  has_many :basic_primary_schools, through: :class_of_schools
  has_many :basic_shugenja_schools, through: :class_of_schools
  has_many :basic_monk_schools, through: :class_of_schools
end

class_of_school.rb:

class ClassOfSchool < ActiveRecord::Base
  belongs_to :school_model, polymorphic: true
  belongs_to :school_class
end

basic_primary_School.rb:

class BasicPrimarySchool < ActiveRecord::Base

  has_many :class_of_schools, as: :school_model, dependent: :destroy
  has_many :school_classes, through: :class_of_schools
end

shugenja_school和monk_schools,与basic_primary_school具有相同的关联。

加入自己的模型:

class CreateClassOfSchools < ActiveRecord::Migration
  def change
    create_table :class_of_schools do |t|
      t.integer :school_class_id
      t.integer :school_model_id
      t.string :school_model_type

      t.timestamps null: false
    end
  end
end

它在学校方面很好地结合,我可以创建school.class_schools,并且我得到了相关的school_classes数组。但另一方面,我也不能这样做。事实上,当我检查school_class.classes_of学校时,我得到空数组。 我通过这样的函数在我的种子文件中建立关联:

def join_schools_with_classes(school_object_name, school_classes_array)
  school_object_name.all.each do |school|
    school_classes = school_classes_array[school.name]
    school_classes.each do |class_name|
      school_class = SchoolClass.find_by(name: class_name)
      school.class_of_schools.create( school_class_id: school_class.id)
    end
  end
end

我的问题:

如何使这种关联双向运作?所以我可以调用ClassSchool.first.class_of_schools返回与此对象关联的所有对象。并且仍然可以调用BasicPrimarySchool.first.school_classes来获取关联的school_class个对象。

1 个答案:

答案 0 :(得分:0)

只需删除SchoolClass关系中的as: :school_model

即可
has_many :class_of_schools, dependent: :destroy

修改

SchoolClass中的关系更改为

has_many :basic_primary_schools, through: :class_of_schools, source: :school_model, source_type: "BasicPrimarySchool"