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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With