ActiveModel Form Objects
Submitting form data is a common feature of web applications – allowing usersto submit their information and giving them feedback whether the information isvalid or not.
ActiveRecord comeswith a powerful set of validators for attributes on a persisted data model. Whendata is not persisted, or used for other non-active record purposes,ActiveModel Helper Modulesreduce the complexity of validations on your plain old Ruby objects.
Routing
Create the routes needed for displaying the form object and posting the data
- Restrict resources to the routes you need using
only:
# config/routes.rbresources:registration,only:[:new,:create]Controller and Actions
Create a controller withnew andcreate actions.
respond_withwill re-render thenewaction if there are any validationerrors on the model- If there are no errors on the model the visitor will be redirected to
showthe current resource. In this case the user will be redirected tosome_other_success_path
# app/controllers/registration_controller.rbclassRegistrationsController<ApplicationControllerrespond_to:htmldefnew@registration=Registration.newenddefcreate@registration=Registration.new(registration_params)@registration.registerrespond_with@registration,location:some_success_pathendprivatedefregistration_params# ...endendView with Registration Form
The view renders a web form with fields to submit.
- Use the ActiveModel object
@registrationin the form - Form generates the endpoint
registration_pathand method of deliverypost - Validation errors will display inline within the form just like ActiveRecord
# app/views/registration/new.html.erb<%=form_for@registrationdo|f|%><%=f.label:first_name,'First Name'%>:<%=f.text_field:first_name%> ...<%=f.submit%><%end%>Object with ActiveModel Conversion, Naming, and Validations
Use any of theActiveRecordValidations inthe model.
- Command pattern used when calling
registermethod. - ActiveRecord validation syntax on attributes.
- ActiveModel::Model mixin includes modules, and includes an initializationmethod.
# app/models/registration.rbclassRegistrationincludeActiveModel::Modelattr_accessor(:company_name,:email,:first_name,:last_name,:terms_of_service)validates:company_name,presence:truevalidates:email,presence:true,email:truevalidates:first_name,presence:truevalidates:last_name,presence:truevalidates:terms_of_service,acceptance:truedefregisterifvalid?# Do something interesting here# - create user# - send notifications# - log events, etc.endendprivatedefcreate_user# ...endendTakeaways
- Keep business logic out of the Controller and Views
- Add validation support to plain Ruby object using ActiveModel includes
- Display data validation errors in the form
- Use ActiveModel naming conventions for generating form endpoints
If you enjoyed this post, you might also like:
About thoughtbot
We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development.Learn more about us.