2012-08-15 3 views
0

사건 :여러 테이블에 어떻게 가입합니까?

테이블 : inne을 수행하는 방법에

  1. teacher :id :name

  2. course :id :name

  3. teachercourse :id :teacher_id :course_id

    r 레일로이 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

+0

받기를 원합니다 : 강좌 이름, 교사 이름 – Yosef

+1

정말 '교사 교습'이 필요하지 않으면 ['has_and_belongs_to_many'] (http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many)로 잘 할 수 있습니다. 그 자체로 모델로 – Chowlett

답변

2

모두 당신의 교사 및 코스 모델도 포함해야 has_many :teachercourses

그런 다음 교사용 모델에서 코드를 작성하는 경우 그 결과는 아래와 같습니다 :

joins(teachercourses: :course) 

편집 : 나는 당신이, 당신은 자바 과정에서 가르치는 모든 교사를 찾고 게시 된 코드 뒤에 의도를 이해한다면

. 그래야 작동합니다 :

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

감사합니다, has_many : teachercourses를 추가해주세요. 레일스 조인을 작성해주세요 - 신입이며 구문을 모른다. – Yosef

+0

컨트롤러에 3 개의 테이블 조인 결과가 필요한 코드를 작성하고있다. – Yosef

+0

답변의 구문이 조인의 실제 구문입니다. 사용하려는 코드를 공유 할 수 있다면 조정할 수 있습니다. – davidrac

관련 문제