Validation of non-model input

I am creating an API with Rails 4.1. One of my calls takes 2 input fields and calls a third-party API call to get more data. He then uses this data to create an ActiveRecord model.

How to check the correct input? I do not make a model of 2 input fields.

Note. Before making a call to a third-party API

they need to be checked.
+4
source share
3 answers

From what you wrote, I would say that you want to look attr_accessorand use ActiveRecordforms to verify the data

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

virtual attributes, ActiveRecord . , , , attr_accessor

@Mohammed, , instance :

#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
+2

attitutes ? , ?

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

Otherwise, you can use the plain old PORO, which extends the module ActiveModel::Modelto simulate the AR model (validations, etc.). You can find more information about this here: http://blog.remarkablelabs.com/2012/12/activemodel-model-rails-4-countdown-to-2013

0
source

Source: https://habr.com/ru/post/1537970/


All Articles