0

I have a mongoid model called Department and a separate model called User, and there is no native relationship between the two models. Because of how the relationships in my application work, I manually store document ID's on the User model.

I am using the Grape framework for Ruby, and it has a filter system that sits on top of Mongoid objects called Entities, and it rejects anything that isnt a mongoid query response object, because this method returns a ruby Array instead of a Mongoid object, my framework gives me errors.

Is there any way to re write my function to return a Mongoid object? or is there any way I can convert an array of Mongoid Objects into one Mongoid object?

## inside Department Model
def self.user_can_access(user = nil)
  if user != nil
    departments = []
    ## department_access_keys are embedded documents belonging to a user
    user.department_access_keys.each do |key|
      departments << BACKBONE::Department.find(key.key)
    end
    departments ## => returns an array of Department Documents that a user has been granted access to
  else
    raise 'user was not defined'
  end
end

2 Answers 2

2

I believe, “Mongoid Object” should be just a hash, so this should work (also note Enumerable.map instead of phpish each { << }):

## inside Department Model
def self.user_can_access(user = nil)
  raise 'user was not defined' if user.nil?

  {
    departments: # return hash here
      user.department_access_keys.map do |key|
        BACKBONE::Department.find(key.key)
      end
  }
end
Sign up to request clarification or add additional context in comments.

Comments

0

Can't you just use find like this?

departments = BACKBONE::Department.find(*user.department_access_keys.map(&:key))

I am not very familiar with mongoid but the Documentation seems to suggest that this is exactly how to achieve what you want.

Criteria#find Find a document or multiple documents by their ids. Will raise an error by default if any of the ids do not match.

Examples:

Band.find("4baa56f1230048567300485c")
Band.find(
  "4baa56f1230048567300485c",
  "4baa56f1230048567300485d"
)
Band.where(name: "Photek").find(
  "4baa56f1230048567300485c"
)

1 Comment

thank you! I have no idea why Grape Entities don't accept arrays, but this solved my problem!

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.