I am working on a small Rails project that simply allows a user to submit a form and the information from the form is sent via an API call to another service for consumption.
Here is my model:
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
And Here is my LineItem
model:
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
I am testing the form out and am trying to get the form to fail if the user submits the form without supplying a :model_number
but the ServiceRequest
object thinks that it's valid?
instead of checking the LineItem
validations.
Anyway to include these validations when I run @service_request.valid?
in my controller?