scaffoldを使ってフォームからデータを保存、追加する際に以下のようなエラーが出てしまいます。
調べてもよく分からなかったのでどなたか助言を宜しくお願いします。
コードも載せておきます。。
questions_controller.rb
ruby
1class QuestionsController < ApplicationController 2 before_action :set_question, only: [:show, :edit, :update, :destroy] 3 layout 'questions' 4 5 # GET /questions 6 # GET /questions.json 7 def index 8 #Question.allで全データを取得し、orderで新しいものから順に並ぶようにしています。 9 @questions = Question.all.order created_at: :desc 10 end 11 12 # GET /questions/1 13 # GET /questions/1.json 14 #新規作成したAnswerオブジェクトに、params[:id]で得られたID番号を指定しています。 15 def show 16 @answer = Answer.new 17 @answer.question_id = params[:id] 18 end 19 20 # GET /questions/new 21 def new 22 @question = Question.new 23 end 24 25 # GET /questions/1/edit 26 def edit 27 redirect_to '/questions' 28 end 29 30 # POST /questions 31 # POST /questions.json 32 #送信されたフォームの内容をもとにQuestionインスタンスを作り、保存しています。 33 def create 34 @question = Question.new(question_params) 35 respond_to do |format| 36 if @question.save 37 format.html { redirect_to '/questions' } 38 format.json { render :show, status: :created, location: @question } 39 else 40 format.html { render :new } 41 format.json { render json: @question.errors, status: :unprocessable_entity } 42 end 43 end 44 end 45 46 # PATCH/PUT /questions/1 47 # PATCH/PUT /questions/1.json 48 def update 49 redirect_to '/questions' 50 end 51 52 # DELETE /questions/1 53 # DELETE /questions/1.json 54 def destroy 55 redirect_to '/questions' 56 end 57 58 private 59 # Use callbacks to share common setup or constraints between actions. 60 def set_question 61 @question = Question.find(params[:id]) 62 end 63 64 # Never trust parameters from the scary internet, only allow the white list through. 65 def question_params 66 params.require(:question).permit(:title, :content, :name, :finished) 67 end 68end 69
_form.html.erb
ruby
1<%= form_for(question) do |f| %> 2 <% if question.errors.any? %> 3 <div id="error_explanation"> 4 <h2><%= pluralize(question.errors.count, "error") %> prohibited this question from being saved:</h2> 5 6 <ul> 7 <% question.errors.full_messages.each do |message| %> 8 <li><%= message %></li> 9 <% end %> 10 </ul> 11 </div> 12 <% end %> 13 14 <div class="field"> 15 <%= f.label :title %> 16 <%= f.text_field :title %> 17 </div> 18 19 <div class="field"> 20 <%= f.label :content %> 21 <%= f.text_area :content, cols:40, rows:10 %> 22 </div> 23 24 <div class="field"> 25 <%= f.label :name %> 26 <%= f.text_field :name %> 27 </div> 28<!-- ユーザーに値を設定させたくない項目は、hidden_fieldを使い、非表示フィールドとして用意する--> 29 <%= f.hidden_field :finished, {value:false} %> 30 31 <div class="actions"> 32 <%= f.submit %> 33 </div> 34<% end %> 35 36
new.html.erb
ruby
1<h1>新しい質問</h1> 2 3<%= render 'form', question: @question %> 4 5<%= link_to 'Back', questions_path %> 6
あなたの回答
tips
プレビュー