I allow users to sign-up and sign-in with Facebook with omniauth-facebook and Devise. It works great except when a validation fails. In this case, Devise's new registration page loads, but without any error messages.
The errors display if I try to register by typing in the fields in the form - just not when a user tries to register using Facebook.
How can I get the model validation errors persist to display on the new registration form?
user.rb
validates :username, :email, uniqueness: true
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.username = auth.info.name.downcase.gsub(" ", "")
user.ensure_username_uniqueness
end
end
def ensure_username_uniqueness
self.username ||= self.email.split("@").first
num = 2
until(User.find_by(username: self.username).nil?)
self.username = "#{username_part}#{num}"
num += 1
end
end
omniauth_callbacks_controller.rb
def facebook
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
devise/registrations/new.html.erb
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<% if object.errors.any? %>
<div class="alert alert-danger" role="alert">
These errors occurred:
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-inputs">
<%= f.input :username, required: true, autofocus: true %>
<%= f.input :email, required: true, autofocus: true %>
<%= f.input :password, required: true %>
<%= f.input :password_confirmation, required: true %>
</div>
<%= f.button :submit, "Sign up", :class=>"btn-info" %>
<% end %>
The problem was that I was using a redirect instead of a render.
After I changed:
redirect_to new_user_registration_url
to:
render :template => "devise/registrations/new"
The error messages showed.