允许用户编辑帐户而不将设计和传递条件中的密码保存到Ruby中的reject_if

我正在开发一个ROR应用程序,当涉及到设计和密码确认时我就陷入了困境。 我希望我的用户能够编辑他们的信息(姓名,位置等)而无需输入和确认他们的密码(除非他们决定更改他们的密码,在这种情况下,这些字段将是必需的。 )

在设计时我做了一些阅读,我注意到这是一个常见的问题。 不幸的是,我尝试了在设计GitHub repo上发布的所有解决方案,但无法解决我的问题。

然而,我发现了一种解决方法,但我希望这是最后一步的问题。 这是我的players.rb文件的一小部分(我有两套帐户 – 玩家和所有者):

  has_one :account, :as => :profile accepts_nested_attributes_for :account, :reject_if => proc { |attributes| attributes['password'].blank? } 

我的accounts.rb文件如下所示:

  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :invited_by, :invited_by_id 

正如它现在设置的那样,玩家可以编辑他们的个人资料而无需输入密码,除非他们正在尝试编辑:密码字段 – 这非常好,而且我想要的结果。 但是,我遇到了一个小问题…… :reject_if => proc { |attributes| attributes['password'].blank? } :reject_if => proc { |attributes| attributes['password'].blank? } 即使在创建新帐户(玩家)时也会执行! 这意味着如果玩家没有输入密码,而不是提示他输入密码,应用程序会刹车!

我需要一些帮助来编写if语句或某些条件,如果Account属于注册(现有)播放器,它基本上只会触发reject_if条件。

我试过:: :reject_if => proc { |attributes| attributes['password'].blank? unless Player.new} :reject_if => proc { |attributes| attributes['password'].blank? unless Player.new}

 if Player.new accepts_nested_attributes_for :account else accepts_nested_attributes_for :account, :reject_if => proc { |attributes| attributes['password'].blank? } end 

我似乎无法弄清楚这一点,所以我决定看看是否有人可以提出意见或建议。 一如既往,我非常感谢您的时间和任何帮助。 谢谢!

在控制器中更新用户时尝试这种代码安静。 这是设计版本1.5.3的更新方法,这两行将起到作用。

  def update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) params[:user].delete(:password) if params[:user][:password].blank? params[:user].delete(:password_confirmation) if params[:user][:password_confirmation].blank? if resource.update_attributes(params[resource_name]) set_flash_message :notice, :updated if is_navigational_format? sign_in resource_name, resource, :bypass => true respond_with resource, :location => after_update_path_for(resource) else clean_up_passwords(resource) respond_with_navigational(resource){ render_with_scope :edit } end end 

我有这个问题困扰了我很长一段时间。 通过遵循“如何”解决了它,然后将:current_password添加到attr_accessible并使用以下内容创建了一个attr_accessor:

 attr_accessor :password, :password_confirmation, :current_password attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :current_password 

如果有其他人遇到这个问题,这里有帮助我的相关链接:

1)如何:允许用户在不提供密码的情况下编辑其帐户

2)编辑用户时无法解析“当前密码不能为空”

3)试图在没有密码的情况下更新用户个人资料信息的问题(这是为我解决的问题)

此外,这里是如何通过Devise&Omniauth与Facebook做同样的事情:

4)用Devise和Omniauth编辑用户