はじめまして、Ruby on rails初学者です。
現在postモデルのtitleとname,そしてcollection_selectを利用してp_cat_idをユーザーのフォームへの投稿しよってGETしようと考えています。
しかし、titleとnameを空欄(collection_selectは選択されている状態)で投稿した時はvalidatesによって表示することはできるのですが、
collection_selectを空欄(titleとnameは選択されている状態)で投稿してもvalidatesを設定しているのにも関わらず、エラー文を表示させることができません。
ちなみに、collection_selectを空欄の状態で保存を実行すると以下のエラーが表示されます。
ActiveRecord::RecordNotFound in PostsController#create Couldn't find Category with 'id'= --- def create @category = Category.find(params[:post][:p_cat_id])#この一文がハイライトさせれています @post = @category.posts.create(post_params) respond_to do |format|
ご教授いただけましたら幸いです。
▶︎postは以下のカラムがあります
Post => Post(id: integer, title: string, name: string, created_at: datetime, updated_at: datetime, p_cat_id: integer, category_id: integer)
▶︎posに紐づくcategoryモデルには以下のカラムがあります
Category => Category(id: integer, p_cat: string, created_at: datetime, updated_at: datetime)
以下は該当のソースコードです。
▶︎formを表示するerb.htmlです
<%= form_for(post) do |f| %> <% if post.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(post.errors.count, "error") %> 件の入力ミスがあります。</h2> <ul> <% post.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :ニックネーム %> <%= f.text_field :name, placeholder: :"名無しさん" %> </div> <div class="field"> <%= f.label :"質問や意見を書こう!" %> <%= f.text_area :title,cols: 60, rows: 8 , placeholder: :"〇〇って本当ですか?"%> </div> <%= f.collection_select :p_cat_id, Category.all, :id, :p_cat ,:prompt => "キーワードを選択してください"%> <div class="actions"> <%= f.submit %> </div> <% end %>
▶︎post.rbです
class Post < ApplicationRecord has_many :comments, dependent: :destroy belongs_to :category validate :add_error_sample def add_error_sample # nameが空のときにエラーメッセージを追加する if name.blank? errors[:base] << "ニックネームは必ず入力して下さい" end # titleが空のときにエラーメッセージを追加する if title.blank? errors[:base] << "質問または意見を入力してください" end if p_cat_id.blank? errors[:base] << "この投稿に関連するキーワードを選択してください" end end end
▶︎postのコントローラーです
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
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。