0

Using Mongoid, I am trying to validate the :code input on the submission form to make sure they are using a proper code that is already stored in the database. There are about 2000+ codes so a helper method array collection wouldn't be feasable.

What is the best way to do this?

I was thinking of doing an inclusion validation, like this:

class Request
include Mongoid::Document 
field :code, type: String      
validates :code, :presence => true, 
                 :inclusion => { :in => proc { Listing.all_codes } }
end

Then the model that has all the stored codes, like this:

class Listing
include Mongoid::Document
field :code, type: String 

  def self.all_codes
    where(:code => exists?) # <--- this is broken
  end
end

But I can't seem to get this to function the way I would like. Any feedback would be much appreciated.

jbearden
  • 1,869
  • 2
  • 19
  • 23

1 Answers1

1

Your Request model looks fine. But the Listing.all_codes needs to return an array of only codes. so:

class Listing
  include Mongoid::Document
  field :code, type: String 

  def self.all_codes
    only(:code).map(&:code)
  end
end
Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109