form_with form object

Posted on December 18, 2024 by Riccardo

The form_with helper accepts an ActiveModel::Model:

<%= form_with model: TeamMemberForm.new do |f| %>
  <%= f.text_field :full_name %><br />
  <%= f.email_field :email %><br />
  <%= f.submit %>
<% end %>

You can create a form object like the following:

class TeamMemberForm
  validates ...

  def self.model_name
    ActiveModel::Name.new(self, nil, 'TeamMember')
  end
end

By using ActiveModel::Name, Rails will take care of filling names and ids as follows:

<input type="text" name="team_member[full_name]" id="team_member_full_name">
<input type="email" name="team_member[email]" id="team_member_email">

So in the controller you can:

params.require(:team_member).permit(:full_name, :email)

PinkLetter

It's one of the selected few I follow every week – Mateusz

Tired of RELEARNING webdev stuff?

  • A 100+ page book with the best links I curated over the years
  • An email once a week full of timeless software wisdom
  • Your recommended weekly dose of pink
  • Try before you buy? Check the archives.