[英]Rails 3: Mongoid validation issue
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. 使用Mongoid,我试图验证提交表单上的:code输入,以确保它们使用的是已经存储在数据库中的正确代码。 There are about 2000+ codes so a helper method array collection wouldn't be feasable.
大约有2000多个代码,因此无法使用辅助方法数组集合。
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.
任何反馈将不胜感激。
Your Request model looks fine. 您的请求模型看起来不错。 But the Listing.all_codes needs to return an array of only codes.
但是Listing.all_codes需要返回仅包含代码的数组。 so:
所以:
class Listing
include Mongoid::Document
field :code, type: String
def self.all_codes
only(:code).map(&:code)
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.