2012-08-15 72 views
0

的情况:如何加入多个表格?

表:

  1. teacher :id :name

  2. course :id :name

  3. teachercourse :id :teacher_id :course_id

怎么办INNE用轨道加入这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 - 我需要连接结果(show行为):

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

你期望从这个查询得到什么? – pkubicki 2012-08-15 08:13:08

+0

希望得到:课程名称,教师名称 – Yosef 2012-08-15 08:14:13

+1

除非您确实需要'Teachercourse',否则您可能会更好地使用['has_and_belongs_to_many'](http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many)作为一种模式。 – Chowlett 2012-08-15 08:17:40

回答

2

你的老师和课程模式双方还应该包含has_many :teachercourses

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

joins(teachercourses: :course) 

编辑:

如果我理解你贴,你正在寻找所有在java课程教教师的代码背后的意图。所以这应该工作:

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

谢谢,我添加has_many:teachercourses。你可以请写轨道加入 - 我是新的,不知道语法 – Yosef 2012-08-15 09:34:31

+0

我写我的代码在控制器需要3表连接结果 – Yosef 2012-08-15 09:35:16

+0

答案中的语法是加入的真正语法,如果你可以在你想要的地方分享代码,我可以调整 – davidrac 2012-08-15 09:53:06