How to validate in a model, data from a controller

后端 未结 4 830
刺人心
刺人心 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:11

    So I tried to edit and add to the @charlysisto question as this was closest to the answer but it did not work so here is the solution I used, as suggested the answer was to send the data from the controller to the model (Although the answers left out using the view to call the controller method) here is my solution

    Model - models/awizard.rb

    class Awizard
      include ActiveModel::Validations
    
      cattr_accessor :valid_data
    
      validate :data_validation :if => lambda { |o| o.current_step == "step1" }
    
      def data_validation
        if self.valid_data == false || self.valid_data.blank?
          errors.add(:valid_data, "not found")
        end
      end
    
      #Other wizard stuff
    
    end
    

    View - awizard/_step1.html.erb

    <% f.label "valid data? %> <% @_controller.valid_data %> #Call controller method to send data to model

    Controller

    class AwizardController < ApplicationController
    
      def valid_data
        data = #data from elsewhere
        if !data.blank?
          Awizard.valid_data = true
        else
          Awizard.valid_data = false
      end
    
    end
    

提交回复
热议问题