I am trying to write some simple code post a form, update the database
and do some validation. I have 2 problems:
- The validation fails but I can’t get hold of the error message
- I can’t get the form to redisplay the previously entered data for the
user to correct.
I have 2 controllers:
user and holiday.
A user can request a new holiday by filling in a form. I have a
request_holiday method in the user controller. My request_holiday.rhtml
sets up a form as follows:
<%= start_form_tag :controller => ‘holiday’, :action => ‘new’ %>
My holiday controller new method does the following:
def new
@holiday = Holiday.new(@params[:holiday])
if @holiday.save
flash[:notice] = "Holiday requested."
redirect_to(:action => "list")
else
flash[:notice] = "Failed."
redirect_to(:controller => 'user', :action => "request_holiday")
end
end
In my holiday model, I check that the dates have been entered sensibly:
def validate
if date_start > date_end
errors.add_to_base("From date cannot be greater than to date")
end
end
I know the validation works because I can get the ‘Failed’ flash notice,
but I can’t seem to get the error message using
error_message_for(:holiday) in the page.
I also can’t seem to get the data to repopulate the form. I normally
access the data in the controller using @params[:holiday] as the params
go into a hash called holiday in the params hash, but when they get
passed back to my form, they don’t live in the holiday hash anymore and
are just normal parameters, e.g
http://localhost:3000/user/request_holiday?date_start%283i%29=15&holiday_type_id=1&date_end%281i%29=2006&date_end%282i%29=2&user_id=&date_end%283i%29=15&date_start%281i%29=2006&approval_id=1&comment=&date_start%282i%29=5
My form uses tags such as
<%= date_select("holiday", "date_end", :order => [:day, :month,
:year]) %>
I’m new to all this say maybe doing it completely wrong, can anyone
help/correct me?
Thanks