【发布时间】:2020-02-27 15:41:00
【问题描述】:
嵌套表单(使用 simple_form gem)创建记录,但不想更新它。
清单有很多问题。 问题属于一个清单。
所有强参数都已设置。
所以,在控制器中:
...
before_action :set_checklist, only: [:show, :edit, :update, :destroy]
...
def new
@checklist = Checklist.new
@checklist.questions.build
end
def create
@checklist = Checklist.new(checklist_params)
if @checklist.save
redirect_to checklists_url, notice: 'Checklist was successfully created.'
...
def edit
end
def update
if @checklist.update(checklist_params)
redirect_to @checklist, notice: 'Checklist was successfully updated.'
else
render :edit
end
end
...
private
def set_checklist
@checklist = Checklist.find(params[:id])
end
def checklist_params
params
.require(:checklist)
.permit(:title, :description,
questions_attributes: Question.attribute_names.map(&:to_sym).push(:_destroy))
end
在视图中:
= simple_form_for(@checklist) do |f|
= f.error_notification
.form-inputs
= f.input :title
= f.input :description
...
%tbody.questions
= f.simple_fields_for :questions do |builder|
= render 'question_fields', f: builder
...
在_question_fields:
%tr.nested-fields
%td
= link_to_remove_association "remove", f, class: 'btn btn-primary btn-xs'
%td
= f.input :title, label: false
%td
= f.input :description, label: false
在清单模型中:
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions,
allow_destroy: true,
reject_if: proc { |att| att['title'].blank? }
有问题的模型:
belongs_to :checklist, optional: true
谢谢
【问题讨论】:
标签: ruby-on-rails updates simple-form nested-forms has-many