Search code examples
ruby-on-railssimple-form

Rails + Simple Form - Create a form with two buttons?


I'm trying to create a form with two buttons. One would be the submit button, but I would also like to have a second button that would allow creating a required element of the form if it does not exist already.

Something like this:

<%= simple_form_for @class do |f| %>
  <%= f.input :title %>
  <%= f.association :teacher %>
  <%= f.button :new_teacher, new_teacher_path, "Add a Teacher" %>
  <%= f.button :submit %>
<% end %>

What I want to happen when the :new_teacher button is clicked is for the new teacher view to open, the user would then fill that out, submit it, and return to creating the class. Is there a sane way to do this?

This is mostly a design issue, it feels like the button should be "within" the form, so that if the user runs into a missing item while filling out the form s/he can easily create it.


Solution

  • One solution that I've found is to use the link_to helper with the link styled as a button. Like this:

    <%= link_to 'Add a Teacher', new_teacher_path, :class => 'button' %>
    

    I tried using button_to instead of link_to and it appears that Simple Form is clever enough to notice that and assume that the button should operate within the context of the form, so I don't get the path I want.