2012-08-15 68 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