Calling update_attributes
fixes the errors you set in rescue
. You should check for errors, and if not, continue, something like this:
@user = current_user begin @user.dob = Date.strptime(params[:user][:dob], '%m/%d/%Y') rescue ArgumentError => ex puts "Setting error." @user.errors.add(:dob, 'The birth date is not in the right format.') end if !@user.errors.any ? && @user.update_attributes(user_params) last_page_visited = session[:last_page_visited] if !last_page_visited.nil? session.delete(:last_page_visited) else flash[:success] = "Profile updated" end redirect_to !last_page_visited.nil? ? last_page_visited : url_for(:controller => 'races', :action => 'index') and return end render 'edit'
Since you are redirect_to ... and return
, you can close the conditional expression and, if you do so, just render the edit page.
You can also add a simple check to your user model:
validates :dob, presence: true
This will always fail if the dob cannot be set for some other unforeseen reason.
To enter a user-entered string to fill in the field when reloading, you can add an accessor to the user model for: dob_string
attr_accessor :dob_string def dob_string dob.to_s @dob_string || dob.strftime('%m/%d/%Y') end def dob_string=(dob_s) @dob_string = dob_s date = Date.strptime(dob_s, '%m/%d/%Y') self.dob = date rescue ArgumentError puts "DOB format error" errors.add(:dob, 'The birth date is not in the correct format') end
Then change the form to set: dob_string
<%= form_for @user do |f| %> <%= f.text_field :dob_string, :value => f.object.dob_string , :size => "20", :class => 'textField', placeholder: 'MM/DD/YYYY' %> <% if @user.errors[:dob] %><%= @user.errors[:dob] %><% end %> <%= f.submit %> <% end %>
And update the controller to set dob_string:
def update @user = User.first begin #@user.dob = Date.strptime(params[:user][:dob], '%m/%d/%Y') @user.dob_string = user_params[:dob_string] end if ! @user.errors.any? && @user.update_attributes(user_params) redirect_to url_for(:controller => 'users', :action => 'show') and return end render 'edit' end def user_params params.require(:user).permit(:name, :dob_string) end