1

我正在为这所潜水学校构建一个应用程序,该学校在每所学校都有多个地点和多个课程。我正在努力做到这一点,以便用户可以在特定学校找到特定讲师教授的所有课程(哦,男孩)。架构如下:

 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)

我希望你能够遵循我正在尝试做的事情。任何和所有的帮助将不胜感激。

4

1 回答 1

1

这就是你应该使用的方式joins

Course.joins(:teacher).where('(teachers.fname ILIKE ? OR teachers.lname ILIKE ?) AND courses.school_id = ?', params[:fname], params[:lname], params[:id])
于 2012-08-26T05:49:24.443 回答