Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shibayu36/9340673d5ff5aed3ea641d3f184c9474 to your computer and use it in GitHub Desktop.
Save shibayu36/9340673d5ff5aed3ea641d3f184c9474 to your computer and use it in GitHub Desktop.
Form object sample on Rails
class UserRegistrationsController < ApplicationController
def new
@user_registration_form = UserRegistrationForm.new
end
def create
@user_registration_form = UserRegistrationForm.new(user_registration_form_params)
if @user_registration_form.save
sign_in(@user_registration_form.user)
redirect_to action: :completed
else
render :new
end
end
def completed; end
private
def user_registration_form_params
params.require(:user_registration_form).permit(
:email,
:password,
:password_confirmation,
:terms_of_service
)
end
end
class UserRegistrationForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :email, :string
attribute :password, :string
attribute :password_confirmation, :string
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
validate :email_is_not_taken_by_another
validates :password, format: { with: /\A[\p{ascii}&&[^\x20]]{8,72}\z/ }, confirmation: { allow_blank: true }
validates :terms_of_service, acceptance: { allow_nil: false }
def save
return false if invalid?
user.save!
UserMailer.with(user: user).welcome.deliver_later
true
end
def user
@user ||= User.new(email: email, password: password)
end
private
def email_is_not_taken_by_another
errors.add(:email, :taken, value: email) if User.exists?(email: email)
end
end
class User < ApplicationRecord
has_secure_password
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: true
validates :password, format: { with: /\A[\p{ascii}&&[^\x20]]{8,72}\z/ }, confirmation: { allow_blank: true }
end
<%= form_with(model: @user_registration_form, url: user_registrations_path, local: true) do |form| %>
...
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment