-
-
Save gouf/3471f5dfb96667110fa46ca5eebdf21f to your computer and use it in GitHub Desktop.
[Ruby - saveする前の値の加工|teratail](https://teratail.com/questions/213240)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
def reassign_order_index(hash) | |
keys = hash.keys | |
values = hash.values | |
reordered_values = | |
values.map.with_index(1) { |x, i| x.update('order' => i) } | |
keys.zip(reordered_values).to_h | |
end | |
# 処理前 | |
params = { | |
'utf8' => '✓', | |
'authenticity_token' => | |
'F98xi8sKXsi7vZmlhtGZpTXpMU0DsDv4FexHYHzVRgXpbkoiJF5429GL1+IIPGZMIo', | |
'hoge' => | |
{ '0' => { 'title' => 'title1', 'order' => '1' }, | |
'1' => { 'name' => 'title2', 'order' => '1' } }, | |
'fuga' => | |
{ '0' => { 'name' => 'name', 'order' => '1' }, | |
'1' => { 'name' => 'title2', 'order' => '1' } }, | |
'commit' => '登録' | |
} | |
hoge = reassign_order_index(params.dig('hoge')) | |
fuga = reassign_order_index(params.dig('fuga')) | |
params.update('hoge' => hoge) | |
params.update('fuga' => fuga) | |
# 処理後 | |
pp params | |
# => | |
# {"utf8"=>"✓", | |
# "authenticity_token"=> | |
# "F98xi8sKXsi7vZmlhtGZpTXpMU0DsDv4FexHYHzVRgXpbkoiJF5429GL1+IIPGZMIo", | |
# "hoge"=> | |
# {"0"=>{"title"=>"title1", "order"=>1}, "1"=>{"name"=>"title2", "order"=>2}}, | |
# "fuga"=> | |
# {"0"=>{"name"=>"name", "order"=>1}, "1"=>{"name"=>"title2", "order"=>2}}, | |
# "commit"=>"登録"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment