When to use FormObject 【Rails】

What is FormObject?

Case:1 you want to solve accepts_nested_attributes_for

class PostForm  include ActiveModel::Model  attr_accessor :contents, :real_size  def save(shoe)
shoe.save!
shoe.reviews.create!(contents: contents) unless contents.empty?
shoe.sizes.create!(real_size: real_size)
end
end
#controllerdef new
@form = PostForm.new
end
def create
@form = PostForm.new(shoes_params)
end

Case2: When the validation is so complicated

class CsvImport
include ActiveModel::Model
attr_accessor :file,
validates :name, presence: true
with_options on: :file do
validate :validationA
validate :validationB
validate :validationC
validate :validationD
validate :validationE
end
def validationA
・・・・・・・・
end
#controllerdef import
@csv_import = CsvImport.new
if @csv_import.valid?(:file)
@csv_import.save!
else
render 'new'
end
end

Wrap up

  1. To avoid accepts_nested_attributes_for.
  2. There are many validations

If you think this article is good, please follow me!

I inform you of an added article

https://twitter.com/tomoharutsutsum

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store