Rails查询联接和关联

时间:2012-08-26 05:41:12

标签: ruby-on-rails ruby-on-rails-3

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

 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 个答案:

答案 0 :(得分:1)

这是你应该如何使用joins

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