Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
thoughtbotthoughtbot
We're live Live on Twitch!

thoughtbot is livestreaming

Work alongside the thoughtbot team as we collaborate with each other and our clients, live. Ask us anything, we're live right now!

Let’s get started!
View all Services
Development
Design
Product
Team and Processes
View all Services
View all Resources
Development
The business of great software
View all Resources

ActiveModel Form Objects

Harlow Ward

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 usingonly:
# config/routes.rbresources:registration,only:[:new,:create]

Controller and Actions

Create a controller withnew andcreate actions.

  • respond_with will re-render thenew action if there are any validationerrors on the model
  • If there are no errors on the model the visitor will be redirected toshowthe 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# ...endend

View with Registration Form

The view renders a web form with fields to submit.

  • Use the ActiveModel object@registration in the form
  • Form generates the endpointregistration_path and 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 callingregister method.
  • 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# ...endend

Takeaways

  • 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:

Sign up to receive a weekly recap from thoughtbot

Looking for even more ways to stay connected?
RSS feedCheck out our feeds

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.


[8]ページ先頭

©2009-2025 Movatter.jp