0

I am using mongoid and I have a embedded structure that looks like this* :

class User
    field :first_name
    field :last_name

    embeds_one :administrateur
    embeds_many :customers
    embeds_one :contractor

now I want to be able to autocomplete a Customer (on both first and last name). I think I could first use a named scope on the User class to retrieve every matching user, but then :

  • I can't come up with the good syntax to "autocomplete" on the first and last_name (I'm not using SQL, so the answer there don't work)
  • Once I have the list of users whose name match the autocomplete term, I have to get the corresponding embedded document(s).

So I believe this kind of code would work :

@customers = Array.new
User.by_name(params[:term]).each do |user|
    @customers << user.customers
end

I just need to implement the named scope User.by_name. Could you help with that ?

*The idea : a User can be an admin, a contractor, or can be a customer (multiple association, because people evolve in life, ya know :D). This structure of having one model that embeds others was selected to facilitate LDAP-based devise authentication.

Community
  • 1
  • 1
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

0

The syntax I came up with for mongoid

class User
    ...
    scope :by_first_name, ->(regex){ 
        where(:first_name => /#{Regexp.escape(regex)}/i)
    }
    scope :by_last_name, ->(regex){
        where(:last_name => /#{Regexp.escape(regex)}/i)
    }
    scope :by_name, ->(regex){ 
        any_of([by_first_name(regex).selector, by_last_name(regex).selector])
    }
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164