2011-03-08 49 views
0

我卡住了。试图去看似简单的验证工作,但我仍然无法得到这个工作。Rails服务器端验证 - belongs_to模型

这里的设置:

型号:

class Course < ActiveRecord::Base 

has_many :locations, :dependent => :destroy 
accepts_nested_attributes_for :locations, :allow_destroy => true 

end 

class Location < ActiveRecord::Base 

    belongs_to :course 

    validates_presence_of :city, 
        :message => "City cannot be blank", 
        :allow_blank => true, 
        :if => Proc.new {|location| location.nil? || (!location.nil? && location.course.format != 'Live') } 

end 

我希望做的是,如果一门课程有什么,但“活”的选择,然后让一个空白的城市要保存在位置表。否则,如果course.format是'Live',则返回一个错误。

我相信它正在验证哪里没有定义位置。但是,当更新课程并将格式更改为“实时”时,验证不起作用。

在rails中,你如何总是引用相关表中的另一列,就像我上面的那个一样?如果这是一门新课程,那么在验证过程中,课程还没有创建,所以course.nil?是真的。

在此先感谢!

回答

0
 
validates_presence_of :city, 
        :message => "City cannot be blank", 
        :allow_blank => true, 
        :if => Proc.new {|location| location.nil? || (!location.nil? && location.course.format != 'Live') } 

在上面的验证中:allow_blank与:if block没有关系。 请尝试像这样

 
validates_presence_of :city, 
        :message => "City cannot be blank", 
        :if => Proc.new {|location| 'your_conditions'} 

Now this validation works when 'your_condition' will return true.