简体   繁体   中英

Ruby on Rails - Passing a large variable from view to controller (avoiding HTTP 414 Request-URI Too Large)

I am attempting to pass a large Ruby hash (@hash) that is already available in my view back to my controller for additional processing. The hash comes from the same controller but it will be processed by a different action.

There are several articles on Stack Overflow about passing a variable (hash or otherwise) from View to Controller using the params hash and they work nicely, however the resulting HTTP GET request is extremely long (in my case) and often a '414 Request-URI Too Large' error is thrown by Apache.

Here is the code I have in my view:

<%= link_to "Go to controller for processing", :controller => 'query', :action => 'parse_data', :hash_contents => @data %>

Here is the code I am using in my controller to process @data:

def parse_data
  # take action on :hash_contents which now contains @data
end

Perhaps I shouldn't be using link_to to handle this but I don't know of an alternative to get data back to my controller. I also heard chatter about using a HTTP POST instead of GET (as apparently you can pass along a hidden field) but I'm not certain how to implement that in this scenario. Any help is greatly appreciated!

To achieve the exact same result with a form using POST, one will have to make hidden fields for every hash key-value, this does not seem very reasonable.

But you can serialize it into one field and deserialize in controller itself, for example - json will do:

<%= form_tag your_controller_action_path, method: :post do %>
  <%= hidden_field_tag 'hash_contents', JSON.dump(@data) %>
  <%= submit_tag "Go to controller for processing" %>
<% end %>

and then JSON.load(params[:hash_contents]) in controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM