Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation of non-model input

I'm building an API with Rails 4.1. One of my calls takes 2 input fields and makes a call to a third party API to get more data. It then uses that data to make an ActiveRecord model.

How should I validate the input? I'm not making a model from the 2 input fields.

Note: They need to be validated before making the call to the third party API

like image 350
Chaseph Avatar asked Oct 20 '22 09:10

Chaseph


1 Answers

From what you've written, I would say you want to look at attr_accessor and use ActiveRecord to validate your form data:

#app/models/model.rb
Class Model < ActiveRecord::Base
    attr_accessor :your, :inputs
    validates :your, :inputs, presence: true
end

This will create virtual attributes which you can then validate using the standard ActiveRecord validation functionality. I believe that, as your model will typically create instance methods for your datatable's attributes, you'll be able to achieve the same functionality with attr_accessor attributes

As mentioned by @Mohammed, you'll then be able to validate the inputs by creating an instance of the model with your data:

#app/controllers/your_controller.rb
Class Controller < ApplicationController
    def create
        @model = Model.new(input_params)
        @model.valid?
    end
    private
    def input_params
        params.require(:model).permit(:your, :inputs)
    end
end
like image 121
Richard Peck Avatar answered Nov 03 '22 07:11

Richard Peck