我想将此案例中的教师技能分配给数学老师,但我不确定我是否有正确的设置。当我尝试将TeacherSkills分配给控制台中的教师时,我遇到下面显示的错误。
我使用过RailsCasts episode#17 但无法清除这些错误。任何人都可以就正确的设置提供一些建议,以实现与STI有很多联系。
m = MathTeacher.first
m.math_teacher_skill_ids
SELECT `math_teacher_skils`.id FROM `math_teacher_skills` WHERE`math_teacher_skills`.`math_teacher_id` = 1 => []
m.math_teacher_skill_ids = [1,2]
ActiveRecord::RecordNotFound: Couldn't find all MathTeacherSkills with 'id': (1, 2) (found 0 results, but was looking for 2)
class Teacher < ActiveRecord::Base
end
class MathTeacher < Teacher
has_many :math_teacher_skills
has_many :skills, :through => :math_teacher_skills
end
class Skill < ActiveRecord::Base
has_many :math_teacher_skills
has_many :teachers, through: :math_teacher_skills
end
class MathTeacherSkill < ActiveRecord::Base
belongs_to :skill
belongs_to :math_teacher
end
#Relevant schema
create_table "math_teacher_skills", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "math_teacher_id"
t.integer "skill_id"
end
create_table "skills", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
end
答案 0 :(得分:0)
Rails提供了一种更简单的方法来建立多对多关系,使用has_and_belong_to_many。请在此处查看更多信息:http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
如果您实现此功能,它可能如下所示:
class MathTeacher < Teacher
has_and_belongs_to_many :skills
end
class Skill < ActiveRecord::Base
has_and_belongs_to_many :math_teachers
end
您可以这样调用(假设您已在数据库中创建了适当的记录):
m = MathTeacher.first
m.skills
m.skills.pluck(:id) # if you want just the ids
答案 1 :(得分:0)
我只想展示与MathTeacher相关的技能,例如代数,而不是像课堂管理这样的通用教师技能。这需要math_teacher_skills表。
我认为使用单表继承时需要连接表,但我愿意进行更正。
class Teacher < ActiveRecord::Base
end
class MathTeacher < Teacher
has_and_belongs_to_many :skills, :join_table => 'math_teacher_skills'
end
class Skills
has_and_belongs_to_many :math_teachers, :join_table => 'math_teacher_skills'
end
create_table "math_teacher_skills", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "math_teacher_id"
t.integer "skill_id"
end
create_table "skills", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
end
如果您想创建或编辑MathTeacher,您可以在这样的视图中分配这些MathTeacher技能。
<%= collection_check_boxes(:math_teacher, :skills_ids, Skill.all,:id, :name) %>