binding.pry 様様


はじめに

投稿機能を実装し、投稿ボタンを押してるのに投稿できない!エラー文も何も出ない!(涙)
原因はわからないがとりあえずMVCの流れに沿って考えてみよう!!

予想

おそらくリクエストを送っているビューか、受け取っているコントローラーが問題となっていそうです。
どちらが原因となっているか判断するために、コントローラーにbinding.pryを記述し確認してみよう!

実際にやってみよう

app/controllers/posts_controllers.rb
def create
    binding.pry
    @poststag = PostsTag.new(post_params)
    if @poststag.valid?
      @poststag.save
      return redirect_to root_path
    else
      render "new"
    end
  end
ターミナル.
[2] pry(#<PostsController>)> post_params
=> <ActionController::Parameters {"title"=>"test", "name"=>"testtag", "user_id"=>1} permitted: true>

今回保存したいカラムは"title","text","name","user_id"なのにpost_paramsの中に"text"が入ってない!!!

原因

app/views/posts/new.html.erb
<div class="message-field">
      <%= f.label :title,  "タイトル" %>
      <%= f.text_area :title, class:"input-message" %>
    </div>
    <div class="message-field">
      <%= f.label :title,  "本文" %>
      <%= f.text_area :title, class:"input-message" %>
    </div>
    <div class="tag-field", id='tag-field'>
      <%= f.label :name, "タグ" %>
      <%= f.text_field :name, class:"input-tag" %>
    </div>

今回はビューに問題があり"title"が重複していることがわかりました。

app/views/posts/new.html.erb
<div class="message-field">
      <%= f.label :title,  "タイトル" %>
      <%= f.text_area :title, class:"input-message" %>
    </div>
    <div class="message-field">
      <%= f.label :text,  "本文" %>
      <%= f.text_area :text, class:"input-message" %>
    </div>
    <div class="tag-field", id='tag-field'>
      <%= f.label :name, "タグ" %>
      <%= f.text_field :name, class:"input-tag" %>
    </div>

真ん中の本文の部分を"text"に変え無事に投稿できました

諦めない

今回デバッグの処理の仕方を復習することができなぜ任意の処理ができないのか?どこが原因なのか?を深く考えることができました。
エラーが出ても俺なら絶対にできるという諦めない