【问题标题】:Validates data of other model when accepts_nested_attributes_for is used使用 accept_nested_attributes_for 时验证其他模型的数据
【发布时间】:2016-10-14 10:25:39
【问题描述】:

我有属于并有很多关系。

问题是我需要检查嵌套属性中的 score 字段是否小于 0,它不应该保存记录而是返回到带有错误消息的表单。

我正在尝试的代码是:

class QuizAttempt < ActiveRecord::Base

  has_many :quiz_answers
  accepts_nested_attributes_for :quiz_answers, reject_if: :invalid_score

  validate :score_greater_than_zero

  private

  def score_greater_than_zero
    errors.add(:quiz_answers, 'must greater than 0') if invalid_score(attributes)
  end

  def invalid_score(attributes)
    attributes['score'].to_i > 0
  end
end


class QuizAnswer < ActiveRecord::Base
  belongs_to :quiz_attempt
end

表单域看起来像包含数组:

name="quiz_attempt[quiz_answers_attributes][5][score]"

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    我需要检查嵌套属性中的 score 字段是否小于 0

    您需要的是访问嵌套对象 (quiz_answers) 并检查它们的属性,而不是 quiz_attempt 的属性:

      def score_greater_than_zero
        if quiz_answers.any? { |answer| answer.score <= 0 }
          errors.add(:quiz_answers, 'must be greater than 0')
        end
      end
    

    【讨论】:

    • 在这种情况下使用reject_if的理由也毫无根据?
    • @LearningROR reject_if 是另外一回事,如果满足条件,它将不会保存嵌套对象,而自定义验证将触发验证错误并且必须重新呈现表单。所以这些有点不同
    • @LearningROR 猜不出为什么,有任何提示/堆栈跟踪吗? :)
    • @LearningROR 0.0 不小于0 :) 将验证更改为&lt;= 0,您将收到错误消息。正如我所说,总是理智地检查事情;)
    • @LearningROR 呵呵 :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多