title: Three model and a many-to-many relation: Is it possible with Rails?
body: <p>I have a problem when doing something as simple as <code>teacher.provider</code>. It returns <code>nil</code> (Just in case, I know I can do teacher.course.provider, but that's not the point of the question).</p>
  
  <p>Let me explain it further:</p>
  
  <p>Among others, I have three classes: <code>Provider</code>, <code>Course</code> and <code>Teacher</code> and one that glues together Course and Teachers establishing a many-to-many relation, <code>StaffProfile</code>.</p>
  
  <h3>Associations</h3>
  
  <p><strong>Provider</strong></p>
  
  <pre><code>class Provider &lt; ActiveRecord::Base
  
      has_many :teachers, dependent: :destroy
      has_many :courses, dependent: :destroy
      has_many :calls, through: :courses
  
  end
  </code></pre>
  
  <p><strong>Course</strong></p>
  
  <pre><code>class Course &lt; ActiveRecord::Base
  
      has_many :staff_profiles, dependent: :destroy
      has_many :teachers, through: :staff_profiles
  
      belongs_to :provider
  
  end
  </code></pre>
  
  <p><strong>Teacher</strong></p>
  
  <pre><code>class Teacher &lt; ActiveRecord::Base
  
      has_many :staff_profiles, dependent: :destroy
      has_many :courses, through: :staff_profiles
  
      belongs_to :provider
  
  end
  </code></pre>
  
  <p><strong>StaffProfile</strong></p>
  
  <pre><code>class StaffProfile &lt; ActiveRecord::Base
  
      belongs_to :course
      belongs_to :teacher
  
  end
  </code></pre>
  
  <h3>Where the problem happens</h3>
  
  <p>I detected it on teachers controller in the action create:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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):</p>
  
  <pre><code>#&lt;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: ""&gt;
  </code></pre>
  
  <p>What am I doing wrong?</p>