Reputation: 13
I've been reading rails and ruby tutorials and just got started with my first project. Everything is going well but I'm having a problem showing validation errors for new users. This is my controller code:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to ''
else
redirect_to '/signup'
end
end
private
def user_params
params.require(:user).permit(:name, :lastname, :nickname, :email, :password)
end
end
And this is my form. I'm omitting all inputs but the nickname one, because I'm testing the validation with it.
<%= form_for(@user) do |f| %>
<div class='form-group'>
<%= f.text_field :nickname, :placeholder => "User name", :class => "form-control", :required => true, :minlength => "2", :maxlength => "24" %>
<div class="text-danger">
<%= @user.errors[:nickname][0] %>
</div>
</div>
<% end %>
I just show the first related error to see if it's working, and avoid any Ifs that would make me doubt if it works or not. The validation on the class is:
class User < ApplicationRecord
has_many :books
has_secure_password
validates :nickname, uniqueness: true
end
When I create a new user by console and try to save it with the same nickname as another it wont save, so the validation works fine. But no error is shown in the view, it just goes back to the signup form and that's all. I'm using ruby 2.2.6 and rails 5.0.1. If I'm missing anything let me know.
Upvotes: 1
Views: 171
Reputation: 3080
Instead of redirect render new
action template:
def create
@user = User.new(user_params)
if @user.save
redirect_to ''
else
render 'new'
end
end
When you do redirect you loose @user
object that contains validation errors. That is why they are not visible in view
Upvotes: 3