4

I'm a Rails noob. I won't lie. I've been tasked with taking two forms and turning them into one dynamic form. This is a Login/Sign Up form. The only issue I have is how to handle the Rails portion of the code. Using jQuery, I could have easily replaced HTML form actions, but how would I approach replacing the action/destination in the rails code based on a login or sign up radio selection.

<%= form_tag login_path, :id => '_login_form' do %>
<% end %>

<%= form_tag sign_up_path, :id => '_sign_up_form' do %>
<% end %>
TSNev
  • 163
  • 2
  • 11

2 Answers2

9

I see two options to solve your problem.

Using javascript you can change the action of a form, based on the radio button selected.

$("#radio").change(function() {
  var action = $(this).val() == "some_value" ? "login" : "sign_up";
  $("#your-form").attr("action", "/" + action);
});

Or you can handle both methods in a single action and treat each of the options separatedly

#view
<p> <%= radio_button_tag :option, "login" %> Orange </p>
<p> <%= radio_button_tag  :option, "sign_up" %> Peach </p>

#controller
if params[:option] == "login"
  #do login
elsif params[:option] == "sign_up"
  #do sign up
end

I hope this helps!

felipeclopes
  • 4,010
  • 2
  • 25
  • 35
1

If the object is to use only one form, but to have different submit buttons go to different form actions, than that seems like a perfect use case for the formaction attribute on submit inputs.

MDN

Note that formmethod is another attribute, if all you want to do is change the method.

Here's a idea of what you might do:

  <%= submit_tag('Sign Up', formaction: 'user#create', formmethod: 'POST') %>

  <%= submit_tag('Log In', formaction: 'user#login', formmethod: 'POST') %>

Any of these form* attributes take precedence over the form action.

cdmo
  • 1,239
  • 2
  • 14
  • 31