如何加入多个表?

时间:2012-08-15 08:04:06

标签: ruby-on-rails ruby-on-rails-3

案例:

表:

  1. teacher :id :name

  2. course :id :name

  3. teachercourse :id :teacher_id :course_id

  4. 如何使用rails对这3个表进行内连接?

    修改(我的模特):

    class Course < ActiveRecord::Base
      attr_accessible :name
      has_many :teachercourses
      has_many :teachers, through: :teachercourse
    end
    
    class Teacher < ActiveRecord::Base
      attr_accessible :name
      has_many :teachercourses
      has_many :courses, through: :teachercourse
    end
    
    class Teachercourse < ActiveRecord::Base
      attr_accessible :course_id, :teacher_id
      belongs_to :course
      belongs_to :teacher
    end
    

    Edit2 - 我需要加入结果(显示操作):

    class CourseController < ApplicationController
      def show
        #not real syntax
        @course=Course.find(join:teacher,teachercourse,teacher :: where course='javacourse');
      end
    end
    

1 个答案:

答案 0 :(得分:3)

您的教师和课程模型都应包含has_many :teachercourses

然后,如果您在教师模型中编写代码,它应该是这样的:

joins(teachercourses: :course)

编辑:

如果我理解您发布的代码背后的意图,那么您正在寻找在Java课程中教授的所有教师。所以这应该有效:

Teacher.joins(teachercourses: :course).where(course: {name: "javacourse"})