Devise – Omniauth – 如果用户通过Facebook登录,则隐藏密码字段

使用Devise与Omniauth我成功地允许用户使用他们的Facebook帐户登录。 在Omniauth wiki的帮助下,我还可以禁用在编辑帐户时输入密码。

我遇到的当前问题是如果他们通过Facebook registrations#edit ,则在我的registrations#edit视图中隐藏密码字段。 作为两个gem的新手我还在努力调整。 因此,在设置必要的辅助方法时,我有点不知所措。

根据维基的指示,这是我的注册控制器的样子:

 class RegistrationsController  true redirect_to after_update_path_for(@user) else render "edit" end end private # check if we need password to update user data # ie if password or email was changed # extend this as needed def needs_password?(user, params) user.email != params[:user][:email] || params[:user][:password].present? || params[:user][:password_confirmation].present? end protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) do |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation) end devise_parameter_sanitizer.for(:account_update) do |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation) end end end 

这是我的registrations#edit视图:

  

Edit




Currently waiting confirmation for:
(leave blank if you don't want to change it)

(we need your current password to confirm your changes)

UPDATE

经过一些广泛的研究,我能够找到一个问题 ,在隐藏输入字段(问题中倒数第二个评论)方面我们正在寻找什么。 唯一的问题是,由于某种原因,它会触发密码validation错误,尽管它不在那里……

  



Currently waiting confirmation for:


(we need your current password to confirm your changes)

在搜索完网站后,我终于找到了如何使用它。

我的第一个业务是从这个设计维基使用第一个代码示例来注册控制器

  def update # For Rails 4 account_update_params = devise_parameter_sanitizer.sanitize(:account_update) # For Rails 3 # account_update_params = params[:user] # required for settings form to submit when password is left blank if account_update_params[:password].blank? account_update_params.delete("password") account_update_params.delete("password_confirmation") end @user = User.find(current_user.id) if @user.update_attributes(account_update_params) set_flash_message :notice, :updated # Sign in the user bypassing validation in case their password changed sign_in @user, :bypass => true redirect_to after_update_path_for(@user) else render "edit" end end 

接下来是添加一个方法来覆盖上面代码上方用户当前密码的validation。 特别感谢Lauri Laine在这篇文章中的答案: 用Devise和Omniauth编辑用户

  # Overwrite update_resource to let users to update their user without giving their password def update_resource(resource, params) if current_user.provider == "facebook" params.delete("current_password") resource.update_without_password(params) else resource.update_with_password(params) end end 

最后我必须添加:current_password作为我的用户模型的虚拟属性,一切正常!

 attr_accessor :current_password 

希望这有助于任何有/将遇到此问题的人。 我知道这让我感到困惑了一分钟,但很高兴我能够把它弄清楚。 将很快与omniauth的twitter gem一起测试。