How to validate in a model, data from a controller

后端 未结 4 827
刺人心
刺人心 2021-01-19 03:15

So I have some data that gets pulled from another rails app in a controller lets call it ExampleController and I want to validate it as being there in my model before allowi

4条回答
  •  别那么骄傲
    2021-01-19 04:04

    The only way to share controller level data with model is through external accessor. Using metaprogramming you can trick the way to pass it to a model instance.

    controller

    def valid_data?            
      data = #data could be nil or not
      result = data.blank? ? false : true
      instance_eval <<-EOV
        def AWizard.new(*args)
          super(*args).tap {|aw| aw.external_valid = #{result}}
        end
      EOV
      result
    end
    

    model

    class AWizard
      attr_accessor :external_valid
    
      def initialize(attributes = {})
        attributes.each do |name, value|
          send("#{name}=", value)
        end
      end
    
      validate :first_step_data, :if => lambda { |o| o.current_step == "step1" };
    
      def first_step_data
        # :external_valid would be true or false according to a valid_data?. Nil would be if valid_data? has not been called
        if external_valid == false
          errors.add ...
        end
      end
    end
    

提交回复
热议问题