2012-02-21 10 views
1

私はsimple_formで使用するために、仮想属性を持つモデルを持っている:Inherited_resourcesカスタムエラー

class Sms < ActiveRecord::Base 
attr_accessor :delayed_send, :send_time_date, :send_time_time 

私はフォームを持っているため/ smses /新しい:

= 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を使用して?

+0

コントローラではなくモデルで検証する必要があるのはなぜですか? – miked

答えて

1

あなたがコントローラで検証している特別な理由がない場合は、検証はモデルにする必要があります:(?またはobject.validするために呼び出す)

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 

コントローラでは、保存トリガされますこれらの検証が実行されます。コントローラーで応答を処理して、必要な場合はアクションを再レンダリングすることができます。

+0

ありがとうございました。そのバリデーションをモデル化して、すべての問題を解決してください。 – BazZy

関連する問題