Railsvalidation上下文

我需要帮助我的ActiveRecord模型。 我使用内置上下文选项进行基于上下文的validation(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 

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


仍然没有答案? 为了解释我的问题:我有一个名为Form的模型,它有很多Field 。 用户应该在提交时看到validation错误,但无论如何都应该保存表单(有和没有错误)。 有不同类型的Field ,每个都有全局validation(以确保数据库一致性)和自己特定的用户定义validation(validation用户输入的数据)。 所以我的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 

在我的控制器中:

  # def create # ... form.attributes = params[:form] form.save!(:global) form.save(:specific) 

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

尝试条件validation

 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 

“在定义validation时指定多个上下文的能力”在Rails 4.1中引入 – 检查validation方法,:on options description

has_nested_attributes_for :model更改为accepts_nested_attributes_for :models

希望这可以帮助。

祝好运。