Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails what is the oppsite of the to_query method?

I have turned, have turned a hash to params using the to_query method.

How to turn it back into a hash?

I have tried this:

require 'rack'
@tester = Rack::Utils.parse_nested_query(params[:search])

In view: <%= @tester.class %>

Which gives NilClass.

The parameters are:

"search"=>"fields%5B%5D=exhb_0&fields%5B%5D=exh0_1&fields%5B%5
D=t_g_a&fields%5B%5D=hp_1&fields%5B%5D=s1&fields%5B%5D=overflade_0&railing%5B%5D
=A-3&railing_m=0&type%5B%5D=ltrappa&wood%5B%5D=wood_6"
like image 809
Rails beginner Avatar asked Dec 21 '25 10:12

Rails beginner


1 Answers

This is a duplicate of this questions: Just use:

Rack::Utils.parse_query(my_query_string)

In order to decode the line in your example, be sure to unescape the string first:

require 'rack'

my_string = 'fields%5B%5D=exhb_0&fields%5B%5D=exh0_1&fields%5B%5D=t_g_a&fields%5B%5D=hp_1&fields%5B%5D=s1&fields%5B%5D=overflade_0&railing%5B%5D=A-3&railing_m=0&type%5B%5D=ltrappa&wood%5B%5D=wood_6'

unescaped_string = URI.unescape(my_string)
# => "fields[]=exhb_0&fields[]=exh0_1&fields[]=t_g_a&fields[]=hp_1&fields[]=s1&fields[]=overflade_0&railing[]=A-3&railing_m=0&type[]=ltrappa&wood[]=wood_6"

params_hash = Rack::Utils.parse_query(unescaped_string)
# => {"fields[]"=>["exhb_0", "exh0_1", "t_g_a", "hp_1", "s1", "overflade_0"], "railing[]"=>"A-3", "railing_m"=>"0", "type[]"=>"ltrappa", "wood[]"=>"wood_6"}
like image 111
gmile Avatar answered Dec 24 '25 02:12

gmile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!