Rails has_and_belongs_to_many状态验证从未通过

时间:2016-11-28 18:43:47

标签: ruby-on-rails ruby

我在投票应用的答案和回复之间有很多关系。每个民意调查都有很多提交,每个提交都可以有很多回复。所以我使用accepts_nested_attributes_for:在我的提交表单中回复,允许用户多次回复。问题是验证嵌套表单中复选框答案(选项)的集合,因为我总是得到一个空白错误。它永远不会让我通过验证,除非我摆脱它,这正确地保存数据。有什么想法吗?

submission.rb

class Submission < ApplicationRecord
  belongs_to :poll
  belongs_to :user
  has_many :replies, inverse_of: :submission, dependent: :destroy

  accepts_nested_attributes_for :replies
end

answer.rb

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

reply.rb

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

submissions_controller.rb

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

_field.html.haml

= 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

1 个答案:

答案 0 :(得分:0)

复选框包含一个空白条目,以确保始终返回某些响应(如果您取消选中所有条目但没有返回任何内容,则不会更改持久列表,并且仍会检查已检查的内容)。

因此请设置accepts_nested_attributes_for以忽略空白记录。

  accepts_nested_attributes_for :replies, reject_if: :all_blank