Rails的验证环境 [英] Rails validation context
问题描述
我需要我的ActiveRecord模型帮助。我必须使用内置的上下文选项验证基于上下文验证(MIS):
I need help with my ActiveRecord model. I have context based validations (mis)using the build-in context options for validations:
validates :foo, :on => :bar, :presence => true
model = Model.new
model.foo = nil
model.valid? # => true
model.save # works as expected
model.valid?(:bar) # => false
model.save(:context => :bar) # fails and returns false
但是用我的模型在 accepts_nested_attributes_for:模型
并调用 parent.save
失败(验证被调用和返回false),任何建议或解决方案?
But using my model in a accepts_nested_attributes_for :model
and calling parent.save
fails (the validation gets called and returns false), any suggestions or solutions?
还是没有答案吗?要更多地解释我的问题:我有一个名为模型表格
其中有许多字段
秒。用户应该看到在提交验证错误,但形式本来也应该保存(有和没有错误)。有不同类型的字段
s,各全球验证(以确保数据库的一致性)和它自己特定的用户自定义的验证(验证用户输入的数据)。所以,我的字段
的神色好歹这样的:
Still no answer? To explain more about my problem: I have a model called Form
which has many Field
s. Users should see validation errors on submit, but the form should be saved anyway (with and without errors). There are different types of Field
s, each with global validations (to ensure database consistency) and its own specific user-defined validations (to validate user-entered data). So my Field
s look someway like that:
# Global validations, to ensure database consistency
# If this validations fail, the record should not be saved!
validates_associated :form, :on => :global
...
# Specific user-defined validations
# If this validations fail, the record should be saved but marked as invalid. (Which is done by a before_save filter btw.)
def validate
validations.each do |validation| # Array of `ActiveModel::Validations`, defined by the user and stored in a hash in the database
validation.new(:on => :specific).validate(self)
end
end
在我的控制器:
# def create
# ...
form.attributes = params[:form]
form.save!(:global)
form.save(:specific)
时使用类似的东西可能在Rails的内置功能?顺便说一句这不是我的实际code,这是相当复杂的。但我希望,你们会得到的想法。
Is something similar possible in Rails using the built-in functionality? Btw this not my actual code, which is quite complicated. But I hope, you guys will get the idea.
推荐答案
尝试有条件的验证
class Customer
attr_accessor :managing
validates_presence_of :first_name
validates_presence_of :last_name
with_options :unless => :managing do |o|
o.validates_inclusion_of :city, :in=> ["San Diego","Rochester"]
o.validates_length_of :biography, :minimum => 100
end
end
@customer.managing = true
@customer.attributes = params[:customer]
@customer.save
这篇关于Rails的验证环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!