2012-08-26 61 views
1

我正在爲這所水肺潛水學校開設一個應用程序,該學校在每所學校都有多個地點和多個課程。我試圖讓它可以讓用戶在特定的學校(哦,男孩)找到所有由特定教師教授的課程。該架構如下:Rails查詢連接和協會

create_table "courses", :force => true do |t| 
    t.string "course_name" 
    t.integer "course_number" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.integer "teacher_id" 
    t.integer "school_id" 
    end 

    create_table "teachers", :force => true do |t| 
    t.string "fname" 
    t.string "lname" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.integer "school_id" 
    end 

我有以下關係成立:

courses belong_to school 
courses belong_to teacher 

teacher belong_to school 

school has_many courses 
school has_many teachers 

我不知道如何做到這一點,但是這是我的(白癡)的嘗試:

#I need to match these queries where course.teacher_id is equal to teacher.id 
teachers = Teacher.where('fname ILIKE ? OR lname ILIKE ?', params[:fname], params[:lname]) 
courses = Course.where('school_id = ?', params[:id]) 

#now to join the above queries 
courses_offered_by_searched_teacher_at_specified_school = courses.joins(teachers) 

我希望你能夠遵循我想要做的。任何和所有的幫助,將不勝感激。

回答

1

這是你應該如何使用joins

Course.joins(:teacher).where('(teachers.fname ILIKE ? OR teachers.lname ILIKE ?) AND courses.school_id = ?', params[:fname], params[:lname], params[:id]) 
+0

謝謝。這是魔術。 – flyingarmadillo

+0

不客氣。謝謝你解決我的答案。 – Mischa