collection_selectを使って、postに紐づくcategoryを選択してもらう機能を実装しています。
そこで、categoryが選択されていなかった場合、保存失敗後にerror文を表示させたいのですが、以下のようなエラーコードがでてきます。
ActiveRecord::RecordNotFound in PostsController#create Couldn't find Category with 'id'=
postコントローラーのdef categoryは以下です。
def create @category = Category.find(params[:post][:p_cat_id]) @post = @category.posts.create(post_params) respond_to do |format| if @post.save format.html { redirect_to @post, notice: 'Post was successfully created.' } format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end
どうかご教授ください。
▶︎以下は今回のバグで関係ありそうなコードーを添付しました。
postのフォーム部分です
<%= form_for(post) do |f| %> <% if post.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> <% post.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :"投稿内容" %> <%= f.text_area :title,cols: 60, rows: 8 %> </div> <%= f.collection_select :p_cat_id, Category.all, :id, :p_cat ,:prompt => "キーワードを選択してください"%> <div class="actions"> <%= f.submit %> </div> <% end %>
postのモデルです(post.rb)
class Post < ApplicationRecord has_many :comments, dependent: :destroy belongs_to :category validates :title, presence: true validates :name, presence: true validates :p_cat_id, presence: true end
あなたの回答
tips
プレビュー