mardi 4 août 2015

Display flash message with model validations

I have the following model validations...

  validates :event_id, :uniqueness => {:scope => :email}
  validates_format_of :email, :with => /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/
  validates_presence_of :email, :first_name, :last_name

..and here is my controller...

def register_learner
    @event = Event.find(params[:event_id])
    begin
      EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
    end
end

This codes work, but the problems is it silently catches the errors. I'd like to display a flash message to the user and in the current page. So I tried this...

   def register_learner
    @event = Event.find(params[:event_id])
    begin
      @registation = EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
      if !@registation.valid?
        flash[:notice] = @registation.errors
      end
    end
   end

...but I get the message undefined method `valid?' for nil:NilClass if the validation fails.

Aucun commentaire:

Enregistrer un commentaire