ddccffvv
ddccffvv

Reputation: 143

Communicating errors generated in model to controller

What is the correct way to propagate errors generated in a model to the user?

For example, I have a Reminder model with a time associated. I also have a static method create_new as follows:

def self.create_new date_string, time_string
    Reminder.new DateTime.parse(#{date_string} #{time_string})
end

In the controller, I'm calling this method to create a new reminder. The form view and controller are straightforward. When the user has a typo in his time field (ie: 112:45 instead of 11:45), parse will raise an error. What's the best way to notify an the user of the location of the typo in the form? I'd like to avoid using javascript on the client side.

Thanks!

Upvotes: 0

Views: 88

Answers (2)

Bart Jedrocha
Bart Jedrocha

Reputation: 11570

I would recommend handling this in the Reminder model with validations. You can either write your own custom validator as explained here or use an existing gem like validates_timeliness.

This allows you to follow Rails' convention over configuration methodology and avoid writing custom create methods on the model or littering your controller code with rescue blocks.

Your controller action would then become

def create
  @reminder = Reminder.new(reminder_params)
  if @reminder.save
    # redirect or whatever
  else
    flash.now[:error] = @reminder.errors.full_messages
  end
end

The same can then be performed in the update action. Hope this helps.

Upvotes: 4

Noel Frostpaw
Noel Frostpaw

Reputation: 3999

In your controller:

def action
  r = create_new params
  -- do stuff
rescue StandardError => e
  flash.now[:error] = e.message
end

In your view you can then just render the output of flash.now[:error] to display the errors if any. I use the flash variable also for all validation messages and what not when updating models or when creation fails.

source: http://guides.rubyonrails.org/action_controller_overview.html#the-flash

Upvotes: 1

Related Questions