Construya 2 URL diferentes a partir de params hash, 1 sobrescribe la otra

On my view, I have 2 URLs I need to create. Each has a separate value for sort but must include all previous settings for ratings.

In order to create this URL, on the controller, as the last step, I muck with the params hash:

params.delete :controller
params.delete :action
params.delete :commit
params.delete :utf8

params[:ratings] = @ratings

@titleparams = params
@dateparams = params

@dateparams[:sort] = "release_date" 
@titleparams[:sort] = "title"

I expect @titleparams and @dateparams to be separate copies of params. Then I add the sort param to each.

The view displays them with the same code but in different THs as:

%a#release_date_header= link_to "Release Date", movies_path(@dateparams)

%a#title_header= link_to "Movie Title", movies_path(@titleparams)

I also have a section at the top of the page to see what @dateparams and @titleparams are coming page to view as. They are the same and I don't understand why.

%hr
=@titleparams
%hr
=@dateparams
%hr

Displays as (ignoring hr for this post)

{"ratings"=>{"G"=>"1", "PG"=>"1"}, "sort"=>"title"} 
{"ratings"=>{"G"=>"1", "PG"=>"1"}, "sort"=>"title"} 

It seems the last sort to be added is the keeper. I.e., the title was the last sort added in the code of the controller's action so it is the last in the two different params lists.

I don't understand why the params copy into the two different variables is acting like pass by reference instead of pass by value. I'm new to Ruby but I haven't seen this before in my Ruby work.

preguntado el 09 de marzo de 12 a las 14:03

1 Respuestas

When you assign a has to another variable in Ruby, you assign the reference, not a copy of the hash. So @titleparams y @dateparams both reference the same underlying Hash as params itself. It's clear, then that, you set :sort a "release_date" and then overwrite with "title".

Trata dup to get an actual copia:

@titleparams = params.dup
@dateparams = params.dup

respondido 09 mar '12, 14:03

Gracias. Esto ayudó mucho. - DFBerry

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.