Rails验证上下文

时间:2011-05-17 14:39:36

标签: ruby-on-rails ruby-on-rails-3 validation activerecord

我的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

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


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

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:5)

"能够在定义验证时指定多个上下文"在Rails 4.1中介绍了 - 检查validate method, :on options description

答案 2 :(得分:2)

仅适用于Rails 5 +:

您正在寻找

with_options on: :custom_event do
  validates :foo, presence: true
  validates :baz, inclusion: { in: ['b', 'c'] }
end

验证或保存使用

model = YourModel.new

# Either
model.valid?(:custom_event)

# Or
model.save(context: :custom_event)

答案 3 :(得分:0)

has_nested_attributes_for :model更改为accepts_nested_attributes_for :models

希望这有帮助。

祝你好运。