class NewSupplier include ActiveAttr::Model attr_accessor :current_employee attribute :supplier_name attribute :email attribute :password attribute :password_confirmation without_current_supplier = { unless: 'current_employee.present?' } validates :supplier_name, presence: true validates :email, email: without_current_supplier validates :password, presence: without_current_supplier, confirmation: without_current_supplier validate :supplier_name_uniqueness validate :employee_uniqueness def save if valid? persist! true else false end end private def persist! employee = Employee.new unconfirmed_email: email, password: password, password_confirmation: password_confirmation raise "Cannot create employee with #{attributes.inspect}" unless employee.save supplier = Supplier.create name: supplier_name supplier.add_manager employee end def employee_uniqueness return if current_employee.present? errors.add :email, :taken if Employee.count_by_email(email) > 0 end def supplier_name_uniqueness return unless current_employee.present? and supplier_name.present? current_suppliers = current_employee.suppliers errors.add :base, 'You already have a supplier with that name' if current_suppliers.map(&:name).include? supplier_name end end