Rails - Getting an error message from the model that is not a Validation error
Using add_to_base
to store the error message seems fine to me, you just need to figure out how to get it into the view.
How about:
flash[:notice] = @reservation.errors.full_messages.to_sentence
Assuming you're going to re-display a form, you could also probably use:
<%= f.error_messages %>
Or possibly:
<%= error_messages_for :reservation %>
Also, you might want to use flash[:error], then you can color it differently with a CSS class in your view.
I think I can see why errors are not being passed back to the user.
The problem is that you are sending a redirect to the user when the action fails instead of just doing a render, that means you lose any variables you set up to use within the request. Instead of adding errors to the flash, just render the edit page and set the flash to a normal message and everything should be fine.
For example:
def add_equip @reservation = Reservation.find(params[:id]) @addedEquip = Equip.find(params[:equip_id]) respond_to do |format| if @reservation.add_equip(@addedEquip) flash[:notice] = "Equipment was added" format.html { redirect_to(edit_reservation_path(@reservation)) } else flash[:error] = 'Error adding equipment' format.html { render :action => :edit } end endend
Now you can continue to use the normal form helpers for displaying error messages.
Also, just a little suggestion for the model code, try to use i18n when possible (including for flash messages in the controller). Although this is mostly a personal preference, it gives a logical home to all your messages and specific text, and alos allows you to create general or default messages which can be changed in one place instead of duplicating the change in multiple models and controllers.
eg.
def add_equip equip if self.reserved.find_by_equip_id(equip.id) self.errors.add_to_base(:already_added) return false elsif !equip.is_available?(self.start, self.end) self.errors.add_to_base(:already_reserved) return false else r = Reserved.new r.reservation = self r.equip = equip r.save endend