三种模式和多对多关系:是否可以使用Rails?

时间:2015-11-19 15:34:52

标签: ruby-on-rails activerecord

在做一些像teacher.provider这样简单的事情时遇到了问题。它返回nil(以防万一,我知道我可以做teacher.course.provider,但这不是问题的重点)。

让我进一步解释一下:

除此之外,我还有三个课程:ProviderCourseTeacher以及一个将课程和教师粘合在一起的课程,建立多对多关系StaffProfile

协会

提供商

class Provider < ActiveRecord::Base

    has_many :teachers, dependent: :destroy
    has_many :courses, dependent: :destroy
    has_many :calls, through: :courses

end

课程

class Course < ActiveRecord::Base

    has_many :staff_profiles, dependent: :destroy
    has_many :teachers, through: :staff_profiles

    belongs_to :provider

end

教师

class Teacher < ActiveRecord::Base

    has_many :staff_profiles, dependent: :destroy
    has_many :courses, through: :staff_profiles

    belongs_to :provider

end

StaffProfile

class StaffProfile < ActiveRecord::Base

    belongs_to :course
    belongs_to :teacher

end

问题发生的地方

我在动作创建中的老师控制器上检测到它:

def create
    course = Course.find(params[:course_id])
    teacher = course.teachers.create(teacher_params)

    # Here is where I have the problem. teacher.provider gives nil instead of returning the associated course provider.
    redirect_to teachers_path(provider_id: teacher.provider.id)
end

鉴于我定义的关系,不应该Rails自动填充通过课程创建的教师中的provider_id字段吗?以防万一,这就是教师创建后的样子(注意缺少provider_id):

#<Teacher:0x007fc0746f7110
 id: 76,
 provider_id: nil,
 first_name: "mermelada",
 last_name: "",
 cv: "",
 linkedin_id: "",
 twitter_id: "",
 created_at: Thu, 19 Nov 2015 15:21:55 UTC +00:00,
 updated_at: Thu, 19 Nov 2015 15:21:55 UTC +00:00,
 photo_file_name: nil,
 photo_content_type: nil,
 photo_file_size: nil,
 photo_updated_at: nil,
 role: "">

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为原因是因为course.teachers.create使用的是StaffProfile关系,而不是Provider关系。

您应该手动分配提供者:

    course = Course.find(params[:course_id])
    teacher = course.teachers.new(teacher_params)
    teacher.provider = ...
    teacher.save!