2

I'm using mongoid, and have the following code:

class Users::User
  include Mongoid::Document
  field :username, type: String
  has_many :emails, class_name: "Users::Email"
end

class Users::Email
  include Mongoid::Document

  field :email, type: String

  belongs_to :user, class_name: "Users::User", inverse_of: :emails
end

database:

#users collection
{
  "_id" : ObjectId("5162de8a359f10cbf700000c"),
  "username" : "bilbo"
}

#emails collection
{
  "_id" : ObjectId("5162de8a359f10cbf700000b"),
  "email" : "bilbo@jenkins.com",
  "user_id" : ObjectId("5162de8a359f10cbf700000c"),
}

I'm trying to find with the following query:

Users::User.includes(:emails).any_of({username: login},{"emails.email"=> login}).first

and I don't know why, but this query ignoring search in emails relation. When login = "bilbo" => true, but when login = "bilbo@jenkins.com" => nil

So, what I'm doing wrong?

ole
  • 5,166
  • 5
  • 29
  • 57

1 Answers1

3

You need a join to do what you're trying to do and Mongoid doesn't have joins. If you only need to access the emails through a user, you could denormalize them and embed them in Users::User.

class Users::User
  include Mongoid::Document
  field :username, type: String
  embeds_many :emails, class_name: "Users::Email"
end

class Users::Email
  include Mongoid::Document

  field :email, type: String

  embedded_in :user, class_name: "Users::User", inverse_of: :emails
end

That way, you can query on a user's emails:

irb(main):011:0> login = "bilbo@jenkins.com"
=> "bilbo@jenkins.com"
irb(main):012:0> Users::User.any_of({username: login},{"emails.email"=> login}).first
=> #<Users::User _id: 5163ee96e44f7b0301000001, username: "bilbo">

If Users::Email's only property is email you could go even a step further and omit the model completely and store the string in an array:

class Users::User
  include Mongoid::Document
  field :username, type: String
  field :emails, type: Array
end

Querying gets even easier:

Users::User.any_of({username: login},{"emails"=> login}).first
=> #<Users::User _id: 5163ef95e44f7b6254000001, username: "bilbo", emails: ["bilbo@jenkins.com"]>