I’m a little lost with mongoid queries. I have a user that has one company.
Here is the model
class Company
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
field :description, :type => String
field :order_minimun, :type => Float
belongs_to :user
def candidate_users
User.where(:company_id => nil)
end
end
class User
include Mongoid::Document
include Mongoid::Timestamps
ROLES = %w[admin company_owner customer]
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
## Database authenticatable
field :email, :type => String, :default => ""
field :encrypted_password, :type => String, :default => ""
validates_presence_of :email
validates_presence_of :encrypted_password
## Recoverable
field :reset_password_token, :type => String
field :reset_password_sent_at, :type => Time
## Rememberable
field :remember_created_at, :type => Time
## Trackable
field :sign_in_count, :type => Integer, :default => 0
field :current_sign_in_at, :type => Time
field :last_sign_in_at, :type => Time
field :current_sign_in_ip, :type => String
field :last_sign_in_ip, :type => String
field :name, :type => String
field :last_name, :type => String
validates_presence_of :name
#validates_uniqueness_of :name, :email, :case_sensitive => false
field :roles_list, :type => Array , :default => ['customer']
validates_uniqueness_of :email, :case_sensitive => false
has_one :company
end
I want to list of the users that not has a company, and the user that owns the company instance.
My first attempt (just of the users which don’t have a company):
def candidate_users
User.where(:company_id => nil)
end
the somethig like this
def candidate_users
User.any_of(:company_id => self.id, :company_id => nil)
end
But I have no luck, that returns all the users.
Someone can helpme with this query?
Thanks in advance.
With mongoid, the
foreign fieldis always on the side of thebelongs_toassociation. SoCompanyobjects will have auser_idfield, butUserobjects won’t have acompany_idfield. So it is “normal” for your queries to return all usersSince there is no notion of join in mongodb, you can achieve this either by reversing the association (user belongs_to company, company has_one user), or you can do two queries :
Still keeping the part about
any_of:any_ofis doing a$orquery for all hashes arguments. By doingUser.any_of(:company_id => self.id, :company_id => nil), you’re supplying only array, which is the same asUser.where(:company_id => self.id, :company_id => nil). What I think you want to do isUser.any_of({:company_id => self.id}, {:company_id => nil})