Thursday, August 25, 2011

Patch to allow link_to with post method

Hello guys,
     If you want to pass additional parameters with post method in link_to than you have to add patch in url_helper of actionpack module of rails.

Here is the simple patch to allow post method with additional parameters in link_to.

Go to the actionpack folder of rails for eg we have rails 2.3.11.

nano /usr/lib/ruby/gems/1.8/gems/actionpack-2.3.11/lib/action_view/helpers/url_helper.rb

Now just replace below lines

line #562
method, href = html_options.delete("method"), html_options['href']
to 
method, href, values = html_options.delete("method"), html_options['href'], html_options.delete("values")
line #570
"if (#{confirm_javascript_function(confirm)}) 
{ #{method_javascript_function(method, url, href)} };return false;"
to
"if (#{confirm_javascript_function(confirm)}) 
{ #{method_javascript_function(method, values, url, href)} };return false;"

line #574 
"#{method_javascript_function(method, url, href)}return false;"
to
"#{method_javascript_function(method, values, url, href)}return false;"

line #590
def method_javascript_function(method, url = '', href = nil)
to
def method_javascript_function(method, values, url = '', href = nil)

and add below code after line #595
 
  if values.is_a?(Hash) && (method == :post || method == :put) 
    values.each do |name,value| 
      submit_function << "var formElement = document.createElement('input'); " 
      submit_function << "formElement.name = '#{name}'; " 
      submit_function << "formElement.type = 'text'; " 
      submit_function << "formElement.value = '#{value}'; " 
      submit_function << "f.appendChild(formElement); " 
    end 
  end 

Finally now you can access the link_to with post action and query parameters.
<%= link_to "Test to click on",
  {:controller => "users", :action => "dummy_action"}, :method => :post, 
   :values => {:arg1 => "Argument1", :arg2 => "Argument 2"}, 
   :class => 'css_class' %>

Hope this post helps you to overcome the problem of link_to during post method.
If you have any suggestion then post comment. 

No comments:

Post a Comment