Question

I have model with virtual attributes, for use in simple_form:

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

I have form for /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 "Отправить"

And i wanna validate all that virtual attributes inside my SmsesController, in create action, and if it invalid - show error. But that doesn't work:

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

How should i add my custom errors, if i using inherited_resources?

Was it helpful?

Solution

If there's not a specific reason you're validating in the controller, the validation should be in the model:

 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

In the controller, a save (or call to object.valid?) will trigger these validations to run. You can then handle the response in your controller to re-render the action if warranted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top