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

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

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 %>

🔗 Parent Note

Top comments (0)