Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, how do you submit a form with a text link?

I am trying to get this form to submit correctly. Here's what I have so far:

<% form_for(:user, :url => update_user_setting_path, :remote => true, :html => {:method => :post, :class => "search_form general_form"}) do |f| %> 

and the button renders with this code:

<li><%= link_to raw("<span class='button approve'><span><span>SAVE</span></span></span>"), :action => 'create' %></li>

I am using action create, is this correct?

Here is the rendered form tag:

<form method="post" data-remote="true" class="search_form general_form" action="/settings/2/update_user" accept-charset="UTF-8">

What am I missing? Thanks for your help!

like image 863
Mitch Moccia Avatar asked Feb 11 '11 01:02

Mitch Moccia


People also ask

What is form tag in Ruby on Rails?

The form_tag Rails helper generates a form withe the POST method by default, and it automatically renders the HTML that we were writing by hand before. Note: We can explicitly specify what HTTP verb to use for the form_tag if we want something other than POST .


2 Answers

No, you are not using link_to properly. You need to use a submit tag to submit your form, not a link_to tag, for example:

<% form_for(:user, :url => update_user_setting_path, :remote => true, :html => {:method => :post, :class => "search_form general_form"}) do |f| %>
  ...
  <li><%= f.submit "Save" %></li>

If you want to use a text link you'll have to have javascript submit the form. For example, if you are using jQuery you could do the following:

<%= link_to 'Save', "#", :onclick=>"$('.search_form').submit()" %>
like image 147
Pan Thomakos Avatar answered Sep 27 '22 22:09

Pan Thomakos


I like Pan's solution but I prefer to use the ID of the form directly which you can get from the dom_id(obj). The form_for helper also uses dom_id(obj) to assign the form's ID. This way you aren't dependent on setting classes by hand or subject to accidentally submitting more than one form that share the same CSS class. It looks a little stranger but I usually have a custom FormBuilder anyway so I just add a generic link_to_submit method to encapsulate this:

<%= link_to 'Save', "#", :onclick => "$('##{dom_id(@user)}').submit()" %>
like image 39
MDaubs Avatar answered Sep 27 '22 23:09

MDaubs