Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify ruby hash in place( rails strong params)

This may be more a ruby question then rails question but I'm pretty sure I was able to do this in a vanilla ruby application.

I have strong params defined.

def trip_params
  params.require(:trip).permit(:name, :date)
end

Now I get those params in a controller method. I want to do this.

def save
  trip_params[:name] = 'Modifying name in place'
  #trip_params[:name] still equals original value passed
end

This never works. Name never changes. BTW: The type of trip_params is ActionController::Parameters

If I do a standard ruby script, it works.

test = {}    
test[:name] = "blah"    
test[:name] = "ok"    
puts test #{:name=>"ok"}
like image 484
Drew H Avatar asked Aug 22 '13 00:08

Drew H


3 Answers

permit returns a new hash with those keys in it, so you're not modifying the real params variable. You're also not saving a reference to the hash trip_params returns, so you get it fresh each call in save.

Try this:

def save
  tp = trip_params
  tp[:name] = 'Modifying name in place'
  # ... use tp later, it'll be in there
end

Or, if you really want it to be used the way you previously did, modify trip_params like so:

def trip_params
  @trip_params ||= params.require(:trip).permit(:name, :date)
end

Now that hash is lazily cached and the same one is returned on subsequent trip_params calls.

like image 55
Nick Veys Avatar answered Nov 20 '22 18:11

Nick Veys


If you really want to change params in controller you can do it on this way:

def save
  params[:trip][:name] = 'Modifying name in place'
  # Now trip_params[:name] is 'Modifying name in place'
end
like image 20
Иван Бишевац Avatar answered Nov 20 '22 20:11

Иван Бишевац


You could also do

def save
  data = trip_params.merge(name: 'new name')
  # use data later
end

If a new hash is merged into an old hash and if there are duplicate keys, the new hash's keys overwrite the old hash's matching keys.

like image 5
Cruz Nunez Avatar answered Nov 20 '22 18:11

Cruz Nunez