Rails验证上下文

Mar*_*her 5 validation activerecord ruby-on-rails ruby-on-rails-3

我需要帮助我的ActiveRecord模型.我有使用内置上下文选项进行验证的基于上下文的验证(mis):

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
Run Code Online (Sandbox Code Playgroud)

但是在a中使用我的模型accepts_nested_attributes_for :model并且调用parent.save失败(验证被调用并返回false),任何建议或解决方案?


仍然没有答案?要解释我的问题的更多信息:我有一个叫做Form多个Fields 的模型.用户应该在提交时看到验证错误,但无论如何都应该保存表单(有和没有错误).有不同类型的Fields,每个都具有全局验证(以确保数据库一致性)和它自己的特定用户定义验证(以验证用户输入的数据).所以我Field看起来像那样:

 # 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
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

 # def create
 # ...
 form.attributes = params[:form]
 form.save!(:global)
 form.save(:specific)
Run Code Online (Sandbox Code Playgroud)

使用内置功能在Rails中可能有类似的东西吗?这不是我的实际代码,这是非常复杂的.但我希望,你们会得到这个主意.

Ant*_*ton 6

尝试条件验证

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
Run Code Online (Sandbox Code Playgroud)


Mac*_*ski 5

"在定义验证时指定多个上下文的能力"在Rails 4.1中引入- 检查验证方法,:on options description


小智 0

改成。has_nested_attributes_for :modelaccepts_nested_attributes_for :models

希望这可以帮助。

祝你好运。