by hakunin · 3y ago · 0 comments
Schema layer purpose is to enforce invariant at the boundary of HTTP.
class ApplicationForm
extend Portrayal
include ActiveModel::Model
class << self
def from_params(params)
new(**filter_params(params))
end
def filter_params(params)
params
.require(model_name.param_key)
.permit(*portrayal.keywords)
.to_hash
.transform_keys(&:to_sym)
end
end
end
class MyForm < ApplicationForm
keyword :first_name
keyword :last_name
validates :first_name, :last_name, presence: true
end
Can use it in a controller action like form = MyForm.from_params(params)
if form.valid?…
# the usual
One of the good things about this approach is that you can also use this object in form_for/form_with in your views.It's a bit dated now, but, I did a short presentation for my local ruby meetup and the slides are here [1]
1. https://slides.com/patrickdavey/rails-5-2-attributes-api#/25