So I have a method in a reservation model called add_equip. This method does some checking to make sure the added piece of equipment is valid (not conflicting with another reservation).
The checks work. If a added piece of equipment shouldn't be added it isn't, and if it should it is.
The problem is I can't figure out how to send the messages back up to the controller to be put in the flash message? I know I must be missing something here, but I've googled for a few hours now and can't really find any clear explanations how how to pass errors back up the the controller, unless they are validation errors.
add_equip in reservations_controller
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[:notice] = @reservation.errors
format.html { redirect_to(edit_reservation_path(@reservation)) }
end
end
end
add_equip in reservation model
def add_equip equip
if self.reserved.find_by_equip_id(equip.id)
self.errors.add_to_base("Equipment Already Added")
return false
elsif !equip.is_available?(self.start, self.end)
self.errors.add_to_base("Equipment Already Reserved")
return false
else
r = Reserved.new
r.reservation = self
r.equip = equip
r.save
end
end
Any help would be greatly appreciated. I know I'm missing something basic here.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With