LoginSignup
1
2

More than 3 years have passed since last update.

【React-Rails】Railsのコントローラーで深すぎるパラメータの値の取得方法【params】

Last updated at Posted at 2021-05-13

axiosから値を取得したい!

フロントがreactでバックエンドにRailsAPIで、フロントからaxiosのputで値をバックエンド側に値を渡そうとしたとき、paramsのデータ構造がが深くなってしまいました。
これを受け取るのに、苦労したので備忘録的に残しておきます。

axiosで渡す値を設定
export const updateHumanApi = (food) => {
    return axios.put(URL),{
        params:{
            human:human,
            human_name:human.name
        }
    })
    .then((res)=>{
        return res.data
    })

コントローラー側

axiosで渡された値をlogger.debugで値を確認するとこのようになりました。深すぎる。。。。

paramsの値
Parameters: {"params"=>{"human"=>{"id"=>1, "user_id"=>1, "name"=>"名前1", "point"=>500, "description"=>"説明文です。", "image"=>nil, "count"=>0, "station"=>"0駅", "deleted"=>false, "created_at"=>"2021-05-11T13:55:09.604Z", "updated_at"=>"2021-05-11T13:55:09.604Z"}, "human_name"=>"名前_0"}, "id"=>"1", "human"=>{}}

名前の値を取得しようとするときの構造を分かりやすく抜き出すと、このようになります。

name
Parameters: {"params"=>{"human"=>{"name"=>"名前1"}}

上記の値を取得しようとすると、このようになります。

RailsController
params[:params][:food][:name]

参考

Railsガイド
https://railsguides.jp/active_record_basics.html#update

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2