2016-03-08 43 views
0

我試圖驗證選擇了「從不」單選按鈕,或選擇了「日期」(使用日期選擇器),因此選擇了日期,因此:expiry_date如何驗證單選按鈕被選中?

:expiresstring type

:expiry_datedate type

 f.input :expires, as: :radio, :collection => ["Never", "Date"] 
     f.input :expiry_date, as: :string, :wrapper_html => { :class => "date_picker"} 

這是我迄今爲止的驗證。

validates :expires, 
    inclusion: { in: ["Never", "Date"], 
    presence: { message: "none selected"}} 
    validates :expiry_date, presence: true 

回答

0

您可以使用custom validation

class Food < ActiveRecord::Base 
    validate :has_expiry_date 

    def has_expiry_date 
    if expires == "Date" && !expiry_date.present? 
     errors.add(:expiry_date, 'needs to be present if food expires') 
    end 
    end 
end