2011-02-24 34 views
2

當且僅當在相關模型中的另一個字段具有特定值時,需要一些幫助來弄清楚如何驗證一個字段。例如:Rails - 在另一個模型中驗證字段

//我的模型

class Course < ActiveRecord::Base 
    has_many :locations, :dependent => :destroy 
    accepts_nested_attributes_for :locations 
end 

class Location < ActiveRecord::Base 
    belongs_to :course 
end 

一門課程可以有很多地方(州,市等),以及一個起始日期。我想有這樣的:「允許location.start_date是空白ONLY IF course.format ==‘DVD’」

在我的地址模式,我想是這樣:

validates_presence_of :start_date, 
         :message => "Start Date can't be blank", 
         :allow_blank => false, 
         :if => Proc.new { |course| self.course.format != 'DVD' } 

後來,當我使用我得到: 私人方法'格式'要求爲零:NilClass

不知道我是否在正確的軌道上。

謝謝!

回答

0

傳遞給if子句的Proc作爲參數傳遞給當前正在驗證的對象實例的塊。所以,你所擁有的|course|確實是|location|。嘗試類似以下內容,看看它是否做你想要的東西:

validates_presence_of :start_date, 
         :message => "Start Date can't be blank", 
         :allow_blank => false, 
         :if => Proc.new { |location| location.course.format != 'DVD' } 
+0

@Brandon ...這是有道理的。我倒退了。現在唯一的問題,因爲這可能是一個不同的問題的邊界線是,當創建一個新的課程時,我得到私人方法'格式'調用nil:NilClass。我相信這是因爲課程實際上還沒有創建,而且該地點還沒有任何可鏈接的地方。 – keldog 2011-02-26 01:40:01

+0

你可以修改你的proc來說'| location | !location.course.nil? && location.course.format!='DVD'' – 2011-02-26 01:47:41

相關問題