Rails Metaprogramming 10 x 0 Me

I am trying to do a dynamic check on an object.

In my application, the user can create questions that will be part of the form, and each question can have a validation.

So, I submit this form and pass the parameter to the following class:

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

      

It almost works. My problem is that subsequent form posts are merging 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"]}>

      

What am I doing wrong?

Thank!

Alex

+3


source to share


1 answer


add_validators

called on every instance QuestionResponse

that adds checks to the class QuestionResponse

. Each new instance adds its own checks to the class, but you still have those added by other (previously created) instances.



0


source







All Articles