Inherited_resources自定义错误

时间:2012-02-21 19:17:52

标签: ruby-on-rails ruby-on-rails-3.2 inherited-resources

我有虚拟属性的模型,用于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中的所有虚拟属性,在create action中,如果它无效 - 显示错误。但这不起作用:

class Admin::SmsesController < Admin::InheritedResources
def create
  @sms.errors.add(:send_time, "Incorrect") if composed_send_time_invalid?
  super
end

如果我使用inherited_resources,我应该如何添加自定义错误?

1 个答案:

答案 0 :(得分:1)

如果您在控制器中验证没有特定原因,则验证应该在模型中:

 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?)将触发这些验证运行。然后,您可以在控制器中处理响应,以便在保证的情况下重新呈现操作。