我有一个模型A,它接受模型B的嵌套属性。模型B条目的数量以及是否需要条目是基于db中的第3个表来决定的。我使用form_for为模型B条目生成包含fields_for的表单。这是验证需要工作的方式:
:required
字段为false,则允许模型B的条目为空,但不应保存该条目,即此条目不应引发验证错误,但应由{{1}拒绝}。 :reject_if
字段为true的条目不允许为空。这些条目不应被:required
拒绝,但在将其保存到db时会引发验证错误。
:reject_if
我应该这样做吗
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类中)或accepts_nested_attributes_for
或validates_presence_of modelB_entry
中的所有内容?首先执行哪个:reject_if或vaildation?
答案 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