Form Object is a very useful pattern in the rail ecosystem because it can tackle a number of issues and antipatterns. In this article we will try to figure out where Type Objects conditions can prove helpful and what protocols allow us to make the most out of them.
What is Form Object?
The form object is a design pattern used to encapsulate the validation-related code and the permanent data into a single entity.
Let’s take a look at the Type Objects example.
Let’s say we have a post model rails and a controller action (posts controller) to construct the new article.
Let’s address the problem, here Post Model contains all validation logic, so it can’t be reused for other entities, such as Admin.
class PostController < ApplicationController def create @post = Post.new(Post_prams) if @post.save render json: @post else render json: @post.error, status: :unprocessable_entity end end private def post_params params.require(:post).permit(:title, :description, :content) end end
class Post < ApplicationRecord validates :title, presence: true validates :content, presence: true end
The best solution is to move the validation logic to a separate, unique responsibility class that we might call PostForm:
class PostForm include ActiveModel: :Model include Virtus.model attribute :id, Integer attribute :title, String attribute :description, String attribute :content, String attr_reader :record def persist @record = id ? Post. find(id) : Post.new if valid? @record.save! true else false end end end
Now, we can use it inside our posts controller like this:
class PostsController < ApplicationController def create @form PostForm.new(post_params) if @form. persist render json: @form. record else render json: @form.errors, status: : unpocessab ly_entity end end private def post_params params.require(:post).permit( :title, :description, :content) end end
Form Object can help to solve a number of different problems when implementing Rails projects and thus, with little effort, it can prove to be a valuable pattern in our toolbox.
Know more about Rails Desingn patterns.