Ask A Question

Notifications

You’re not receiving notifications from this thread.

Validation errors on model available in the controller but not in the view - help please?

Iain asked in Rails

I've got a password reset form setup that is not displaying any errors at all and it's killing me. If I input a password (but no confirmation) -- I expect to see 2 errors.

Those 2 errors are in the controller (I can print them out). But they're not showing up in the view...help! I'm definitely calling a render rather than redirect but cannot see what I'm doing wrong :S.

It's also not working when I manually add an error as in the first if statement :(

Code is:

before_action :get_user, only: [:edit, :update]

def edit
end

def update
if params[:user][:password].empty?
@user.errors.add(:password, "can't be empty")
puts "Error count for user = #{@user.errors.count}"
render 'edit'
elsif @user.update(user_params)
log_in @user
flash[:success] = "Password has been reset."
redirect_to @user
else
puts "Error count for user = #{@user.errors.count}"
render 'edit'
end
end

-- View
<% provide(:title, 'Reset password') %>

Reset password

<%= "Error count for user = #{@user.errors.count}" %>

<%= form_with(model: @user, url: password_reset_path(params[:id], local: true)) do |f| %> <%= render 'shared/error_messages', object: f.object %> <%= "Error count for user = #{@user.errors.count}" %> <%= hidden_field_tag :email, @user.email %>
<%= f.label :password %> <%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Password Confirmation" %> <%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.submit "Update password", class: "btn btn-primary" %>
<% end %>
Reply

UPDATE

Checked that the object was the same in controller and view. On first load – the @user.object_id.to_s variable is identical in the controller and view.

When re-rendered, the object_id in the view is the same as previously. The object_id in the controller is changing. So the controller object has the errors, the model object in the view does not (it's not updating).

...continuing to search through the code!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,733+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.