5

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps a form object would work for you: http://robots.thoughtbot.com/activemodel-form-objects

Comments

0

Are will these inputs be used as attibutes in the model? If so, why not initialise a new object and test for validity?

def new
  foo = Foo.new(inputs)
  foo.valid?
end

Otherwise you can use a plain old PORO that extends ActiveModel::Model module to imitate an AR model (validations and so forth). You can find more detail on this here: http://blog.remarkablelabs.com/2012/12/activemodel-model-rails-4-countdown-to-2013

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.