Skip to content

Instantly share code, notes, and snippets.

@thaichors3000
Last active January 31, 2020 10:50
Show Gist options
  • Save thaichors3000/f7b583d4f8dd539a78a42cface680054 to your computer and use it in GitHub Desktop.
Save thaichors3000/f7b583d4f8dd539a78a42cface680054 to your computer and use it in GitHub Desktop.
class User < ApplicationRecord
has_one :car
validates :username, presence: true,
validates :username, length: { maximum: 100 }
validates :age, numericality: { only_integer: true }
end
class Car < ApplicationRecord
enum vehicle_type: %i[suv van compact]
belongs_to :user
validates :user, presence: true
validates :model, presence: true
end
class UserAdultForm < BaseForm
USER_ATTRIBUTES = %i[username age]
CAR_ATTRIBUTES = %i[model vehicle_type]
attr_accessor(*USER_ATTRIBUTES)
attr_accessor(*CAR_ATTRIBUTES)
validates :age, numericality: { greater_than_or_equal_to: 18 }
def initialize(params = {})
@user = initialize_user(params)
@car = initialize_car(params)
super(
params.merge(
user.slice(*USER_ATTRIBUTES)
).merge(
car.slice(*CAR_ATTRIBUTES)
)
)
end
def valid?
errors.clear
super
user.valid?
delegate_validation_on(user, :username)
delegate_validation_on(user, :age)
car.valid?
delegate_validation_on(car, :model)
delegate_validation_on(car, :vehicle_type)
errors.empty?
end
def vehicle_types
Car.vehicle_types.keys
end
private
attr_reader :user
attr_reader :car
def persist!
ActiveRecord::Base.transaction do
user.save!
car.save!
end
end
def initialize_user(params)
user = params[:id] ? User.find(params[:id]) : User.new
user.attributes = params.slice(*USER_ATTRIBUTES)
user
end
def initialize_car(params)
car = user.car || user.build_car
car.attributes = params.slice(*CAR_ATTRIBUTES)
car
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment