DEV Community

n350071๐Ÿ‡ฏ๐Ÿ‡ต
n350071๐Ÿ‡ฏ๐Ÿ‡ต

Posted on

Form object pattern in Rails

๐Ÿค” Motivation

In the case of ..,

  • The form in the view isn't made from only one model
  • You don't want to write the form specific logic in the model

You might want to introduce a form object. Because it isolates the responsibility from model/view/controller to form.

๐Ÿ‘ Solution

1. Introduce a form class

# forms/dog_form.rb
class DogForm
  include ActiveModel::Model

  attr_accessor  :id, :name

  validates :name, presence: true

  # This method is for getting dog collection with some ๅˆถ็ด„ 
  def search
    rel = Operation
    rel = rel.where(id: id) if id.present?
    rel = rel.where("name LIKE (?)", "%#{name}%") if name.present?
    rel = rel.newer
  end

  def save
    return false if invalid?
    # do something ( save, notify, logging)
    true
  end
end
Enter fullscreen mode Exit fullscreen mode

2. Use it in any controller

# dogs_controller.rb
def index
  @serach_form = DogForm.new(params[:search])
  @dogs = @serach_form.search.page params[:page]
end
Enter fullscreen mode Exit fullscreen mode

3. The erb will be like this

# dogs/index.html.erb
<%= form_for(@serach_form, as: 'search', url: manage_dogs_path, html:{method: :get}) do |f| %>
  <div>
    <div><%= f.text_field :id %></div>
    <div><%= f.text_field :name %></div>
  </div>
  <%= f.button t('words.actions.search') %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”— Parent Note

Top comments (0)