borjagvo
borjagvo

Reputation: 2081

Three model and a many-to-many relation: Is it possible with Rails?

I have a problem when doing something as simple as teacher.provider. It returns nil (Just in case, I know I can do teacher.course.provider, but that's not the point of the question).

Let me explain it further:

Among others, I have three classes: Provider, Course and Teacher and one that glues together Course and Teachers establishing a many-to-many relation, StaffProfile.

Associations

Provider

class Provider < ActiveRecord::Base

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

end

Course

class Course < ActiveRecord::Base

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

    belongs_to :provider

end

Teacher

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

Where the problem happens

I detected it on teachers controller in the action create:

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

Given the relations I defined, shouldn't Rails autofill the provider_id field in the teacher created through the course? Just in case, this is what the teacher looks like once created (note the lack of 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: "">

What am I doing wrong?

Upvotes: 0

Views: 62

Answers (1)

blat
blat

Reputation: 64

I think the reason is because course.teachers.create is using the StaffProfile relationship, and not the Provider one.

You should manually assign the provider:

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

Upvotes: 1

Related Questions