我正在尝试动态验证对象。
在我的应用程序上,用户可以创建将成为表单一部分的问题,并且每个问题都可以进行验证。
所以,我发布了这个表单,并将参数传递给下面的类:
require 'ostruct'
class QuestionResponse < OpenStruct
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
extend ActiveModel::Callbacks
def fields
@table.keys
end
def add_validators
stored_questions = AdmissionForm.find(self.form_id).questions.all
questions = fields.select{|f| f.to_s[0]=="q"}
questions.each do |question_param|
question = stored_questions.select{|f| f["id"] == question_param.to_s.gsub("q_","").to_i}.first
unless question.validations.empty?
validations = "validates :#{question_param} , #{question.validations.join(",")}"
self.class.instance_eval validations
end
end
end
def initialize(*args)
super
add_validators if self.fields.any?
end
def persisted? ; false ; end;
end
它几乎可以工作。我的问题是后续表单帖子连接 ActiveModel::Errors
#<ActiveModel::Errors:0x00000004432520
@base=#<QuestionResponse q_7="", q_6="", form_id="1">,
@messages=
{:q_7=>["cant be blank", "cant be blank"],
:q_6=>["cant be blank", "cant be blank"]}>
我究竟做错了什么?
谢谢!
亚历克斯