Rails服务器端验证 - belongs_to模型

时间:2011-03-08 07:49:24

标签: ruby-on-rails

我被困住了。试图找到一个简单的验证工作,但我仍然无法使其工作。

以下是设置:

型号:

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?是的。

提前致谢!

1 个答案:

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