rails:嵌套表单中的验证vs reject_if

时间:2016-10-20 17:26:56

标签: ruby-on-rails validation nested-forms activemodel

我有一个模型A,它接受模型B的嵌套属性。模型B条目的数量以及是否需要条目是基于db中的第3个表来决定的。我使用form_for为模型B条目生成包含fields_for的表单。这是验证需要工作的方式:

  1. 如果对应的:required字段为false,则允许模型B的条目为空,但不应保存该条目,即此条目不应引发验证错误,但应由{{1}拒绝}。
  2. :reject_if字段为true的条目不允许为空。这些条目不应被:required拒绝,但在将其保存到db时会引发验证错误。

    :reject_if
  3. 我应该这样做吗

    1. 位于class modelA < ApplicationRecord has_many :modelBs, dependent: :destroy accepts_nested_attributes_for :modelBs, reject_if: :not_required_and_blank? def not_required_and_blank? # return true if modelB.entry is blank && modelB.required_entry? is false end end class modelB < ApplicationRecord belongs_to :modelA validates :modelB_entry, presence: true, if: :required_entry? def required_entry? ModelC.find(:id).required end end 的{​​{1}}选项(在modelA类中)和:reject_if方法(在modelB类中)或
    2. accepts_nested_attributes_for
    3. 中的所有内容
    4. validates_presence_of modelB_entry中的所有内容?
    5. 首先执行哪个:reject_if或vaildation?

1 个答案:

答案 0 :(得分:2)

reject_if and validations have different purpose.

suppose you have a nested model modelB with two fields name and title, with name as mandatory field.

Use of reject_if

In the controller #new action, you decide to build the first nested object yourself to give user a better UI experience so that he can easily see what else he can add to the form. or the user himself clicks on the "+ Add more" button. But then decides to leave modelB blank and not entering any info in it. Now, if you don't use reject_if but you have validations the user will get the error message saying field is blank, and he won't be able to submit the form, unless he clicks on remove button.

So, in this case you will check if all fields are blank in the reject_if, if that is the case we can ignore the record, else let the model do it's work.

Also, keep in mind that reject_if does not guarantees data integrity. As any typical RoR app has multiple entry points.

In my opinion, you should go with the first option. Use both reject_if and validations