Rails 3 with Devise for Authentication - 如何手动创建用户?

发布于 2024-10-10 16:39:31 字数 139 浏览 1 评论 0原文

我想手动创建新的用户,而不强迫他们验证他们的电子邮件地址。

这个想法是允许现有用户自动添加他们的朋友,而不需要他们注册。这对于我正在努力解决的业务案例来说是有意义的。

如何通过 Devise 实现这一目标?

I would like to manually create new Users, without forcing them to verify their email address.

The idea is to allow existing users to automatically add their friends without requiring their registration. It makes sense for the business case I'm working to solve.

How can this be achieved with Devise?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小霸王臭丫头 2024-10-17 16:39:31

skip_confirmation! 方法适用于任何confirmable 模型。

@user = User.new params[:user]
@user.skip_confirmation! # Sets confirmed_at to Time.now, activating the account
@user.save

不过,用户帐户将被激活。如果您不希望这样,请继续阅读。

Devise 使用条件回调来生成确认令牌并发送电子邮件。仅当 confirmation_required? 返回 true 时才会调用回调。在您的模型上重新定义它:

def confirmation_required?
  false
end

但是,这将使 active_for_authentication? 方法始终返回 true,因为它会考虑是否需要确认。我们还必须重新定义:

def active_for_authentication?
  confirmed? || confirmation_period_valid?
end

这样,帐户将保持不活动状态,并且不会发送确认电子邮件。您必须通过在记录上调用 confirm! 或仅将 confirmed_at 设置为任意日期来手动激活用户。

这确实是一个黑客,但它应该可以工作。

供参考:confirmable.rb

The skip_confirmation! method is available to any confirmable model.

@user = User.new params[:user]
@user.skip_confirmation! # Sets confirmed_at to Time.now, activating the account
@user.save

The user account will be activated though. If you don't want that, continue reading.

Devise uses conditional callbacks to generate the confirmation token and send the email. The callbacks will be called only if confirmation_required? returns true. Redefine it on your model:

def confirmation_required?
  false
end

However, this will make the active_for_authentication? method always return true because it takes whether or not confirmation is required into account. We have to redefine that as well:

def active_for_authentication?
  confirmed? || confirmation_period_valid?
end

This way, the account will stay inactive and no confirmation email will be sent. You will have to manually activate the user by calling confirm! on the record or just setting confirmed_at to any date.

It's quite a hack, but it should work.

For reference: confirmable.rb

残月升风 2024-10-17 16:39:31

我只想补充一下,以供将来参考,自 Devise 2.2 以来,现在还提供了一个 skip_confirmation_notification! 方法,该方法基本上可以完成 Matheus 帖子中的所有操作,而无需重新定义模型中的方法。

I just want to add for future reference that since Devise 2.2 there is now a skip_confirmation_notification! method available as well which basically does everything from Matheus' post without redefining the methods in the model.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文