
Question:
I am currently working with form in ruby on rails 3. So in my project form I have a button to sign users out of this project. However, the strange thing is, that the button_to
tag closes my whole form and i cannot use my submit button anymore.
So I tried a lot, but i do not understand why this happens.
So this is my form:
<%= form_for @project, html: { class: "form-horizontal project" } do |f| %>
<div>
<%= f.label :users, 'Project Users:', :class => 'control-label', style: 'margin-bottom: 20px' %>
<div>
<% @project.users.order('last_name').each do |user| %>
<div style="margin-bottom: 15px">
<%= user.name %>
<%= button_to 'Sign Out', sign_user_out_project_path(user_id: user.id, id: @project), method: :delete, class: 'btn btn-danger btn-xs pull-right', style:'margin-right: 600px; margin-top: -20px' %>
</div>
<% end %>
</div>
</div>
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
projects_path, :class => 'btn btn-default' %>
<% end %>
In my opinion this code looks fine, as all tags are perfectly closed. However, i think there might be some magic when using button_to
so maybe someone knows a better way to do what I want to do.
Thanks!
Answer1:Don't put a button_to
inside your form.
As per the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to" rel="nofollow">docs</a>:
<blockquote>(button_to
) Generates a form containing a single button that submits to the URL created by the set of options
--
HTML forms have a <a href="http://www.w3schools.com/html/html_forms.asp" rel="nofollow">clear spec</a>, and you should adhere to that whenever you implement one.
Including a form within a form causes the "outer" form to stop working (HTML can't process another <form>
before </form>
.
The simple answer is to remove your button_to
from within your form & put it outside, <em>or</em> (in your case), replace it with another element (link_to
). If you want the link to look like a button, you can use <a href="https://stackoverflow.com/a/15695784/1143732" rel="nofollow"><button>
markup</a> to create a button:
<%= form_for @project, html: { class: "form-horizontal project" } do |f| %>
<div>
<%= f.label :users, 'Project Users:', :class => 'control-label', style: 'margin-bottom: 20px' %>
<div>
<% @project.users.order('last_name').each do |user| %>
<div style="margin-bottom: 15px">
<%= user.name %>
<%= link_to '<button>Sign Out</button>'.html_safe, sign_user_out_project_path(user_id: user.id, id: @project), method: :delete, class: 'btn btn-danger btn-xs pull-right', style:'margin-right: 600px; margin-top: -20px' %>
</div>
<% end %>
</div>
</div>
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
projects_path, :class => 'btn btn-default' %>
<% end %>