我在投票应用的答案和回复之间有很多关系。每个民意调查都有很多提交,每个提交都可以有很多回复。所以我使用accepts_nested_attributes_for:在我的提交表单中回复,允许用户多次回复。问题是验证嵌套表单中复选框答案(选项)的集合,因为我总是得到一个空白错误。它永远不会让我通过验证,除非我摆脱它,这正确地保存数据。有什么想法吗?
class Submission < ApplicationRecord
belongs_to :poll
belongs_to :user
has_many :replies, inverse_of: :submission, dependent: :destroy
accepts_nested_attributes_for :replies
end
class Answer < ApplicationRecord
belongs_to :question, inverse_of: :answers
has_and_belongs_to_many :replies
validates :name, presence: true, length: { minimum: 2, maximum: 150 }
end
class Reply < ApplicationRecord
belongs_to :question
belongs_to :submission, inverse_of: :replies
has_and_belongs_to_many :answers
validates :raiting_field, presence: true, allow_nil: true
validates :answers, presence: true
end
class SubmissionsController < ApplicationController
before_action :set_poll, only: [:new, :create]
def new
@submission = Submission.new
@poll.questions.each do
@submission.replies.build
end
end
def create
@submission = Submission.new(submission_params)
@submission.poll = @poll
@submission.user = current_user
respond_to do |format|
if @submission.save
format.html { redirect_to [@poll.client, :polls],
flash: { success: "The survey has been submitted successfully."}}
format.js {}
format.json {
render json: @submission, status: :created, location: @submission
}
else
format.html { render 'new' }
format.js {}
format.json {
render json: @submission.errors, status: :unprocessable_entity
}
end
end
end
private
def set_poll
@poll = Poll.find(params[:poll_id])
end
def submission_params
params.require(:submission).permit(replies_attributes: [:raiting_field, :question_id, answer_ids:[]])
end
end
= f.hidden_field :question_id, value: @submission.poll.question.id
= f.association :answers,
collection: @submission.poll.answers,
as: :check_boxes, label: false, include_hidden: false
答案 0 :(得分:0)
复选框包含一个空白条目,以确保始终返回某些响应(如果您取消选中所有条目但没有返回任何内容,则不会更改持久列表,并且仍会检查已检查的内容)。
因此请设置accepts_nested_attributes_for
以忽略空白记录。
accepts_nested_attributes_for :replies, reject_if: :all_blank