Rails验证提交的嵌套字段的数量

时间:2017-03-21 00:02:53

标签: ruby-on-rails ruby forms validation

我有一个用于创建投票的form_for。民意调查有许多poll_options,也称为嵌套属性。

问题 - 如何验证poll_options的数量?只有一个选项进行投票是没有意义的。

这是我的模特:

class PollOption < ApplicationRecord
  belongs_to :poll
  has_many :poll_responses
  accepts_nested_attributes_for :poll_options,
    reject_if: proc { |attributes| attributes['value'].blank? },
    allow_destroy: true

  validates :poll_options, length: {
    minimum: 1, too_short: "must be at least 2.",
    maximum: 5, too_long: "can be 5 at most."
  }

以下是我的观点:

<%= f.fields_for :poll_options do |poll_option| %>
  <%= render 'poll_option_fields', f: poll_option %>
<% end %>

我得到的错误与视图中的渲染线有关:

exception reentered

我也尝试过这种验证,但它既不起作用,也没有产生错误:

  def validates(value)
    if value.count < 1
      errors.add(:base, "must have at least 2 choices.")
    end
  end

更新:这是我的请求参数:

{"utf8"=>"✓", "authenticity_token"=>"6h+wZ+RUAOIp8iXFX0V9t0MSxTGtFHpe7PZS3fJeF3JejaIbAm2jidLyg0qYII26NYX+F1BH6FHWNCFJ7nzymQ==", "poll"=>{"user_id"=>"2", "active"=>"true", "question"=>"Example - Which of these do you like best?", "poll_options_attributes"=>{"0"=>{"value"=>"a", "_destroy"=>"0"}, "1"=>{"value"=>"b", "_destroy"=>"0"}, "2"=>{"value"=>"c", "_destroy"=>"0"}, "3"=>{"value"=>"", "_destroy"=>"0"}}}, "commit"=>"Save Poll", "controller"=>"polls", "action"=>"create"}

1 个答案:

答案 0 :(得分:1)

您应该在投票模型中验证,您可以在Poll中添加自定义验证,如下所示:

def validates_amount_of_polls
  if poll_options.size < 2
     errors.add(:base, "must have at least 2 choices")
  end
end