使用OmniAuth和Devise

时间:2017-06-18 05:07:10

标签: ruby-on-rails devise omniauth omniauth-facebook

我允许用户使用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

设计/注册/ 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 %>

1 个答案:

答案 0 :(得分:0)

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

我改变之后:

redirect_to new_user_registration_url

为:

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

显示错误消息。