2011-05-17 55 views
5

我需要我的ActiveRecord模型的帮助。我必须使用内置的上下文选项验证基于上下文验证(MIS):Rails验证上下文

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 s。用户应该在提交时看到验证错误,但表单应该保存(无论有没有错误)。有不同类型的Field s,每个类型都有全局验证(以确保数据库一致性)以及它自己的特定用户定义验证(验证用户输入的数据)。所以我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的内置功能?顺便说一句,这不是我的实际代码,这很复杂。但我希望,你们会明白这个主意。

回答

0

更改has_nested_attributes_for :modelaccepts_nested_attributes_for :models

希望这会有所帮助。

祝你好运。

+0

没有,遗憾的错字。我的意思是,当然'accept_nested_attributes_for'!谢谢btw :) – 2011-05-18 08:36:31

+0

我认为验证上下文':bar'是错误的,但':on =>:create'或':on =>:update'应该没问题。 – Danil 2011-05-19 22:03:08

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