我正在开发一个小型Rails项目,该项目只允许用户提交表单,表单中的信息通过API调用发送到另一个服务进行消费。
这是我的模特:
class ServiceRequest
include ActiveModel::Model
include ActiveModel::Validations
extend ActiveModel::Naming
attr_accessor :first_name, :last_name, :prefix, :contact_email, :phone_number,
:address, :address2, :city, :state, :zip_code, :country,
:address_type, :troubleshooting_reference, :line_items
validates_presence_of :first_name, :last_name, :contact_email, :phone_number,
:address, :city, :state, :zip_code, :country, :address_type,
:troubleshooting_reference
def initialize(attributes = {})
super
@errors = ActiveModel::Errors.new(self)
@api_response = nil
end
def line_items_attributes=(attributes)
@line_items ||= []
attributes.each do |i, params|
@line_items.push(LineItem.new(params))
end
end
def save
conn = Faraday.new(url: "#{Figaro.env.arciplex_url}") do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
@api_response = conn.post do |req|
req.url "/api/v1/service_requests?token=#{Figaro.env.api_token}"
req.headers['Content-Type'] = 'application/json'
req.body = self.to_json
end
validate!
end
def validate!
# If successful creation, do nothing
unless [200, 201].include?(@api_response.status)
Rails.logger.debug(@api_response.inspect)
errors.add(:base, @api_response.body)
else
return @api_response.body
end
end
end
这是我的LineItem
模型:
class LineItem
include ActiveModel::Model
include ActiveModel::Validations
attr_accessor :item_type, :model_number, :serial_number, :additional_information
validates_presence_of :item_type, :model_number, :serial_number
end
我正在测试表单,如果用户提交表单时没有提供:model_number
但ServiceRequest
对象认为它是valid?
而不是LineItem
,那么我会尝试让表单失败检查@service_request.valid?
验证。
无论如何,当我在控制器中运行{{1}}时,要包含这些验证吗?