Uniones y asociaciones de consulta de Rails

I am building an app for this scuba school that has muiltiple locations and muiltiple courses at each school. I am trying to make it so users can find all the courses taught by a particular instructor, at a particular school (oh boy). The schema is as follows:

 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"

  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"

Tengo configuradas las siguientes relaciones:

courses belong_to school
courses belong_to teacher

teacher belong_to school

school has_many courses
school has_many teachers

I have no clue how to do this, but this is my (idiotic) attempt:

#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)

I hope you are able to follow what I am trying to do. Any and all help would be appreciated.

preguntado el 26 de agosto de 12 a las 06:08

1 Respuestas

This is how you are supposed to use joins:

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

Respondido 26 ago 12, 07:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.