dperitch
dperitch

Reputation: 1939

Forward parameters in the specific order (using link_to helper)

I want to forward parameters from one view to the another one, and this is what I managed to do. But I want to pass those parameters in the specific order. On first request, after I send the form, I get the params in the order that I want. For example:

http://www.example.com/someurl?project_id=1&start_date=2016-01-10&end_date=2016-01-20

Then, after I have those params in the view, I generate a link with link_to helper, in this kind of a way:

= link_to "link text", some_specific_path(some_id, {"project_id"=>"1", "start_date"=>"2016-01-10", "end_date"=>"2016-01-20"})

But then, the link will be generated as:

http://www.example.com/someurl?end_date=2016-01-20project_id=1&start_date=2016-01-10

So, the problem is - when I send a form, parameters get added to the url in the order of how they appear in the form. But, when you generate a link with link_to helper and path helper, then parameters are always added in the alphabetical order, no matter how they actually appear.

Upvotes: 1

Views: 722

Answers (3)

Marat Amerov
Marat Amerov

Reputation: 406

It is Rails bug https://github.com/rails/rails/issues/1146

also, consider send params between request in sessions.

Upvotes: 1

mtkcs
mtkcs

Reputation: 1716

It's good idea to define a helper here:

module ApplicationHelper
  def link_to_with_sorted_params(text, path, _params)
    prepared_params = _params.map { |k,v| "#{k}=#{v}" }.join("&")
    prepared_link = "#{path}?#{prepared_params}"

    link_to text, prepared_link
  end
end

Call it

=link_to_with_sorted_params("hi", users_path, {"user" => 1, "res" => 2})
#=> <a href="/users?user=1&amp;res=2">hi</a>

Upvotes: 1

guitarman
guitarman

Reputation: 3310

Ok, my solution for you, but it's realy urly:

hash = {"project_id"=>"1", "start_date"=>"2016-01-10", "end_date"=>"2016-01-20"}
query_string = hash.map{|k,v| "#{k}=#{v}"}.join("&")
link_to "link text", some_specific_path(some_id) + "?" + query_string

Upvotes: 1

Related Questions