我有一个带有虚拟属性的模型,用于simple_form:
class Sms < ActiveRecord::Base
attr_accessor :delayed_send, :send_time_date, :send_time_time
我有/smses/new:的表格
= simple_form_for([:admin, resource]) do |f|
...
.clear
.field.grid_3
= f.input :delayed_send, :as => :boolean, :label => "Отложенная отправка на:"
.clear
.field.grid_3
= f.input :send_time_date, :as => :string, :input_html => { :class => 'date_picker' }, :disabled => true, :label => "Дату:"
.clear
.field.grid_1
= f.input :send_time_time, :as => :string, :disabled => true, :label => "Время:", :input_html => { :value => (Time.now + 1.minute).strftime("%H:%M") }
.clear
.actions.grid_3
= f.submit "Отправить"
我想在创建操作中验证SmsesController中的所有虚拟属性,如果它无效,则显示错误。但这不起作用:
class Admin::SmsesController < Admin::InheritedResources
def create
@sms.errors.add(:send_time, "Incorrect") if composed_send_time_invalid?
super
end
如果我使用继承资源,我应该如何添加自定义错误?
如果没有在控制器中验证的特定原因,则验证应该在模型中:
class Sms < ActiveRecord::Base
#two ways you can validate:
#1.use a custom validation routine
validate :my_validation
def my_validation
errors.add(:send_time, "Incorrect") if composed_send_time_invalid?
end
#OR 2. validate the attribute with the condition tested in a proc.
validates :send_time, :message=>"Incorrect", :if=>Proc.new{|s| s.composed_send_time_invalid?}
end
在控制器中,保存(或调用object.valid?)将触发这些验证运行。然后,您可以在控制器中处理响应,以便在必要时重新呈现操作。