1

我有带有虚拟属性的模型,用于 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

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

4

1 回答 1

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

于 2012-02-21T21:11:48.420 回答