robb
robb

Reputation: 294

Doing search queries on many to many relationships

Can I share my headches with you? I'm trying to do a search with this piece of code. (Line with arrow)

def index
    search = params[:user][:subject_ids]
---->   @users = User.includes(:subjects).where(role: 'instructor')
    @user = current_user
end

It's a many to many association. I have users, enrollements and subjects. I have instructors who have signed up to teach 1-5 courses. When I do the search, I get list of all the instructors, not just the ones teaching the subject I queried for.

Not sure where to go from here.

Associations

class User < ActiveRecord::Base
  has_many :enrollments, dependent: :destroy
  has_many :subjects, through: :enrollments
end

class Subject < ActiveRecord::Base

  has_many :enrollments, dependent: :destroy
  has_many :users, through: :enrollments

end

class Enrollment < ActiveRecord::Base 

  belongs_to :user
  belongs_to :subject

end

Thank you for your time.

Upvotes: 0

Views: 53

Answers (1)

Toby 1 Kenobi
Toby 1 Kenobi

Reputation: 5037

You forgot to put the search parameter in your query. Your line should look something like this:

@users = User.includes([:enrolments,:subjects]).where("user.role" => 'instructor', "subjects.id" => search)

Upvotes: 3

Related Questions