Question

I have a mongomapper model like this:

class ChildTemplate

  include MongoMapper::Document
  plugin MongoMapper::Plugins::IdentityMap

  key :name,            String, :required => true, :unique => true
  key :description,     String
  key :config,          Array

  key :used_parameters, Array
  many :parameters, :in => :used_parameters

  validate :parameters_in_config

  def parameters_in_config
    found_parameters = Set.new

    config.each do |line|
      params = line.scan("<([-+*]{2})(.+)\1>")
      unless params.empty?
        found_parameters |= params.transpose[1]
      end
    end

    unless found_parameters == Parameter.find(used_parameters).fields(:name).to_set 
      errors.add(:parameters, 'Incorrect')
    end
  end

end

class Parameter

  include MongoMapper::Document
  plugin MongoMapper::Plugins::IdentityMap

  key :name,          String
  key :description,   String
  #more keys

end

The problem is this line:

unless found_parameters == Parameter.find(used_parameters).fields(:name).to_set 

Here, I have built up a Set called found_parameters that contain the names of parameters used. For validation, I need to make sure this set is equal to the names of the parameters whose ids are in the used_parameters array.

It doesn't work the way I've tried and other things I've tried include:

used_parameters.name
used_parameters[:name]
parameters.name
parameters[:name]
Parameter.find(used_parameters)[:name]

etc...

I just can't figure out the proper query. Also I'm always having trouble finding proper documentation for mongomapper. Everything is quite brief on the website with few examples, and especially for a noob at ruby and mongo as a whole it's extra difficult.

So please, if someone could explain more about querying associated documents, I'd appreciate it.

Was it helpful?

Solution

I'm currently using an each-loop to get the names and store them in a seperate collection:

parameters.each do |par|
    used_param_names << par.name
end

This works as it should, but I would like a more elegant way in that MongoMapper probably provides a possibility to get the collection of names in a single statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top