den*_*icz 6 validation ruby-on-rails activemodel
我正在开发一个小型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
Run Code Online (Sandbox Code Playgroud)
这是我的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
Run Code Online (Sandbox Code Playgroud)
我正在测试表单,并且如果用户提交表单而没有提供表单,我试图让表单失败:model_number但是ServiceRequest对象认为它valid?不是检查LineItem验证.
无论如何,当我@service_request.valid?在我的控制器中运行时包括这些验证?