0

User has_many items Item belongs_to Client

Using mongoid (i don't think it's mongoid specific, but anyway) i need to gather all clients by given user. Currently i use:

@clients = current_user.items.map{|c| c.client}

but for sure it's not good, and not acceptable. What is the best way for implementation?

3
  • 1
    That's not horrible or anything. But it's probably best if you describe via some pseudo code what you'd like your ultimate syntax to look like. Basically it sounds like you'd like to apply some syntactic sugar to your code, and have cleaner code, maybe something like: clients = user.all_clients Commented Aug 23, 2012 at 17:05
  • First of all, as result is have an array, and it's not very handy. Second, i'm not sure, but i think with huge amount of records it's not good to put it on ruby's shoulders? (again, it's mongodb) Commented Aug 23, 2012 at 17:17
  • Got it, I think you have a couple of options, either hand craft a SQL statement that does what you want, or use ActiveRecord includes (Eager loading). Deciding between the two is probably application specific. link Check out section on Eager Loading Commented Aug 23, 2012 at 18:19

1 Answer 1

2

To not run into the N+1 problem I would do something like this.

# first you retrieve all client ids
ids = current_user.items.map(&:client_id)

# then you retrieve all clients at once
@clients = Client.in(id: ids)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.