DRY form partial for create and update

dry, forms, ruby-on-rails

Solution

ActiveRecord has the `new_record?` method which you can use to decide what to show on the form:

<% form_for @user do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name, 'Full name' %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :username %><br />
    <%= f.text_field :username %>
  </p>
  <p>
    <%= f.label :email, 'Email address' %><br />
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>
  <p>
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
  </p>
  <% if @user.new_record? %>
    <p>
      <%= f.check_box :eula %>
      <%= f.label :eula, 'I agree to the terms and conditions' %>
    </p>
  <% end %>
  <p><%= f.submit @user.new_record? ? "Create my account" : "Update my account" %></p>
<% end %>

Problem

I have a _form.html.erb form partial which helps to DRY up my code but I need the form to have different labels depending on if I am creating a new user or updating an existing user. Here is my form partial. I don't need to show the eula checkbox during update and I also need to replace the "Create my account" submit button text to something more appropriate when doing an update. ``` <% form_for @user do |f| %> <%= f.error_messages %> <p> <%= f.label :name, 'Full name' %><br /> <%= f.text_field :name %> </p> <p> <%= f.label :username %><br /> <%= f.text_field :username %> </p> <p> <%= f.label :email, 'Email address' %><br /> <%= f.text_field :email %> </p> <p> <%= f.label :password %><br /> <%= f.password_field :password %> </p> <p> <%= f.label :password_confirmation %><br /> <%= f.password_field :password_confirmation %> </p> <p> <%= f.check_box :eula %> <%= f.label :eula, 'I agree to the terms and conditions' %> </p> <p><%= f.submit "Create my account" %></p> <% end %> ``` Which one of the following is the best way to do this? - have 2 separate form partials, one for create and one for update - have 1 form partial but have conditional labels based on the action (is this possible?) - factor the common part into a partial and reuse that in the create and update forms If I were to do conditional form how would I check which action is being performed?

Original source