Mongoid Relational Queries Syntax

I'm having issues using a has_and_belongs_to_many relationship. I have the following:

class User
  include Mongoid::Document

  has_and_belongs_to_many :subjects
end

class Subject
  include Mongoid::Document
  field :name, :type => String
  attr_accessible :name
  has_and_belongs_to_many :users
end

Then in my controller I am trying to find all users that have a particular subject:

class UsersController < ApplicationController
    def index
        @users = User.where('subjects.name' => 'Physics')
    end
end

Am I going about this the right way?

Upvotes: 1

Views: 173

Answers (2)

Zippie
Zippie

Reputation: 6088

There is probably only one subject named Physics. I think the code should be something like:

@subject = Subject.find_by_name('Physics')
@users = @subject.users

This should be a nested route and probably not in the index page of the UsersController. http://guides.rubyonrails.org/routing.html#nested-resources

EDIT: Or actually if not a nested route, you should put that code in the SubjectsController like this:

def index
    @subject = Subject.find(params[:id])
    @users = @subject.users
end

or if you pass the name as the parameter:

def index
    @subject = Subject.find_by_name(params[:name])
    @users = @subject.users
end

EDIT2: Based on what Harrison James told me in the comments:

Subject.find(:all, :conditions => ["name LIKE ?", "%#{params[:name]}%"])

Upvotes: 1

Ganesh Kunwar
Ganesh Kunwar

Reputation: 2653

def index
    @subjects = Subject.where('name' => 'Physics')
    @subjects.each do |subject|
     @users = subject.users
    end
end

This gives the users per subject.

Upvotes: 1

Related Questions