0

使用Mongoid,我試圖驗證提交表單上的代碼輸入,以確保它們使用已存儲在數據庫中的正確代碼。大約有2000多個代碼,因此輔助方法數組集合將不可行。Rails 3:Mongoid驗證問題

這樣做的最好方法是什麼?

我在想這樣做的夾雜物驗證,像這樣:

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

然後具有所有存儲的故障碼,這樣的模式:

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

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

但我似乎無法讓它按我想要的方式運作。任何反饋將不勝感激。

回答

1

您的請求模型看起來不錯。但是Listing.all_codes需要返回唯一代碼的數組。所以:

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

    def self.all_codes 
    only(:code).map(&:code) 
    end 
end