LoginSignup
0

More than 3 years have passed since last update.

Tweet app コントローラの記載ミス

Posted at

投稿はできるがtext, image_urlが保存されないトラブルについて

確認して言った手順
1.投稿は完了するがビューへ反映されない。
2.ターミナルなどにはエラー文が出てこない。
3.データベースのtweetsテーブルを確認したところ保存されていない事がわかった。
4.tweets_controller.rbのcreate アクション内でbinding.pryを設け、paramsの中身を確認。

 13: def create
 => 14:   binding.pry
    15:   Tweet.create(tweet_params)
    16: end

[1] pry(#<TweetsController>)> params
=> <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"0OetjLpGY/lhw+49IYsP6z/lYBicOBakjt7zB/n3lXPLq1ShQdX3hu5sZApmOfmY+rCNTiNpym1PH0lREvaCnw==", "tweet"=>{"image"=>"〇〇.jpg", "text"=>"test"}, "commit"=>"SEND", "controller"=>"tweets", "action"=>"create"} permitted: false>

5.image と text の情報は取得できていることがわかる。
6.次にtweet_paramsを確認すると、user_id しか取得できていないことがわかった。

[2] pry(#<TweetsController>)> tweet_params
  User Load (0.4ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
  ↳ app/controllers/tweets_controller.rb:42
=> {:user_id=>1}

7.したがって、ストロングパラメータで指定しているパラメータに不備があることがわかる。
8. ストロングパラメータにおいて、image と text も許可(permit)するように記載することで解決できる。

"tweet"=>{"image"=>"〇〇.jpg", "text"=>"test"},

※tweetの中にimageとtextが入ってるので出してあげる必要がある。
9.最後に下記の内容へ変更したら正常となった。

tweets_controller.rb
Before
def tweet_params
    {user_id: current_user.id}
 end

After
def tweet_params
  params.permit(:image, :text).merge(user_id: current_user.id)
end

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
0