nested_form gemを使用しましたが、2つのテーブル(Project、Question)のフィールドを持つフォームを作成しようとしています。ネストされたフォームをレールに保存できませんでした。
マイモデル:
class Project < ApplicationRecord
has_many :questions
accepts_nested_attributes_for :questions
end
class Question < ApplicationRecord
belongs_to :project
end
マイコントローラ:
class ProjectsController < ApplicationController
layout 'application'
def index
@projects = Project.all
end
def show
@project = Project.find(params[:id])
end
def new
@project = Project.new
@questions = @project.questions.build
end
def create
@project = Project.new(project_params)
@project.save
respond_to do |format|
if @project.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: @project }
else
format.html { render :new }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
private
def project_params
params.require(:project).permit(:name, question_attributes: [:id, :content, :_delete])
end
end
マイビュー:
<%= nested_form_for(@project) do |f| %>
<% if @project.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% @project.errors.full_messages.each do |message| %>
<li>
<%= message %>
</li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<%= f.fields_for :questions do |builder| %>
<%= render "question_fields", :ff => builder %>
<% end %>
<p>
<%= f.link_to_add "Add a questions",:questions %>
</p>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
そして、私のスキーマファイル:
create_table "projects", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "questions", force: :cascade do |t|
t.integer "project_id"
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["project_id"], name: "index_questions_on_project_id", using: :btree
end
そして_question_fieldsファイルは次のとおりです。
<p>
<%= ff.label :content, "Question" %>
<%= ff.text_area :content%>
<%= ff.link_to_remove "Remove this task"%>
</p>
表プロジェクトが保存されますが、テーブルの質問saved.Whyことができませんでしたか?
変更後のコード
def project_params
params.require(:project).permit(:name, questions_attributes: [:id, :content, :_delete])
end
のこの行は、私は次のエラーを取得する:
1エラーが保存されているから、このプロジェクトを禁止:
質問プロジェクトは
を存在している必要があります変更を適用しましたが、今回は何も保存できませんでした。
def project_params
params.require(:project).permit(:name, questions_attributes: [:id, :content, :project_id, :_delete])
end
'_question_fields'コードがありません。 – Wukerplank