前提・実現したいこと
rails でタスク管理のサイトを作っており新規カードを作れるようにしたい
発生している問題・エラーメッセージ
新規でカードを製作する時にタイトルを空で製作した特にエラーが発生しました。
エラーメッセージ Showing /Users/yukihiro/task/app/views/card/new.html.erb where line #4 raised: undefined method `id' for nil:NilClass <div class='container'> <%= form_with model: @card, url: { action: :create }, html: { class: 'cardnewForm' }, local: true do |f| %> <%= f.hidden_field :list_id, value: @list.id %> <% if @card.errors.any? %> <p class="text-danger">タイトルは1~255文字以内で入力してください</p> <% end %> Rails.root: /Users/yukihiro/task Application Trace | Framework Trace | Full Trace app/views/card/new.html.erb:4:in `block in _app_views_card_new_html_erb__3948908429696352605_70184326787920' app/views/card/new.html.erb:3:in `_app_views_card_new_html_erb__3948908429696352605_70184326787920' app/controllers/card_controller.rb:16:in `create' Request Parameters: {"utf8"=>"✓", "authenticity_token"=>"mCRIn7nBpecY/DU2KOMYWZi9XsMgZ+w2uTsgym3/bEhSZy/UGMoJ1iP/mQHSirp+Jf5rPAfzJrBuxN0OsvBCWw==", "card"=>{"list_id"=>"7", "title"=>"", "memo"=>"lo"}, "commit"=>"作成する", "list_id"=>"7"} ### 該当のソースコード
rails card_controller.rb <code> class CardController < ApplicationController before_action :set_card, only: %i(show edit update destroy) def new @card = Card.new @list = List.find_by(id: params[:list_id]) end def create @card = Card.new(card_params) if @card.save redirect_to :root else @lists = List.where(user: current_user) render action: :new end end def show end def edit @lists = List.where(user: current_user) end def update @lists = List.where(user: current_user) if @card.update_attributes(card_params) redirect_to :root else render action: :edit end end def destroy @card.destroy redirect_to :root end private def card_params params.require(:card).permit(:title, :memo, :list_id) end def set_card @card = Card.find_by(id: params[:id]) end end
new.html.erb <div class="cardnewPgae"> <div class='container'> <%= form_with model: @card, url: { action: :create }, html: { class: 'cardnewForm' }, local: true do |f| %> <%= f.hidden_field :list_id, value: @list.id %> <% if @card.errors.any? %> <p class="text-danger">タイトルは1~255文字以内で入力してください</p> <% end %> <div class="cardnewForm_title"> <%= f.label :title %> <%= f.text_field :title, autofocus: true, class: "form-control", placeholder: "カード名" %> </div> <div class="cardnewForm_memo"> <%= f.label :memo %> <%= f.text_area :memo, autofocus: true, class: "form-control", placeholder: "詳細" %> <div class="text-center"><%= f.submit "作成する", class: "submitBtn" %></div> </div> <% end %> </div> </div>
試したこと
@lists = List.where(user: current_user)の記述をnew,createアクションに入れてみましたがエラーになります
補足情報(FW/ツールのバージョンなど)
回答1件
あなたの回答
tips
プレビュー