DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on

2 1

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

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil β€” patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Ruby application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay