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?
If I were to do conditional form how would I check which action is being performed?
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 %>
Wrap the <form> tag around the call partial tag and put the submit button in the respective views. Only put the eula check box in the create view.
You can create a variable in the new and update views and use that as your label name.
<%= f.label email, emaillabel %>
[Edit] If you need to pass variables to a partial use this:
<%= render :partial => 'form', :locals => { :myvar => myvar } %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With