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
也许表单对象对你有用 : http : //robots.thoughtbot.com/activemodel-form-objects
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.