Rails 使用 OmniAuth 和 Devise 的验证未在视图中显示错误

Rails Validations not Showing Errors in View with OmniAuth and Devise

我允许用户使用 omniauth-facebook and Devise 注册和登录 Facebook。它工作得很好,除非验证失败。在这种情况下,Devise 的新注册页面加载,但没有任何错误消息。

如果我尝试通过在表单中​​的字段中键入内容进行注册,则会显示错误 - 而不是当用户尝试使用 Facebook 进行注册时。

如何让模型验证错误持续显示在新注册表单上?

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 %>

问题是我使用的是重定向而不是渲染。

我改后:

redirect_to new_user_registration_url

至:

render :template => "devise/registrations/new"

错误信息显示。