Skip to content

Instantly share code, notes, and snippets.

@bbozo
Created August 4, 2015 09:55
Show Gist options
  • Select an option

  • Save bbozo/50f8638787d6eb63aff4 to your computer and use it in GitHub Desktop.

Select an option

Save bbozo/50f8638787d6eb63aff4 to your computer and use it in GitHub Desktop.
class Signup
include Virtus
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
attr_reader :user
attr_reader :company
attribute :name, String
attribute :company_name, String
attribute :email, String
validates :email, presence: true
# … more validations …
include User::Validations # add User model validation
# Forms are never themselves persisted
def persisted?
false
end
def save
if valid?
persist!
true
else
false
end
end
private
def persist!
@company = Company.create!(name: company_name)
@user = @company.users.create!(name: name, email: email)
end
end
class User < ActiveRecord::Base
# you can extract this into a app/models/user/validation.rb but I prefer to have
# little pieces of function like this in one place
module Validations
extend ActiveSupport::Concern
included do
# add validations here
end
end
include Validations
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment