【问题标题】:Devise Omniauth-facebook bypass rails validations设计 Omniauth-facebook 旁路验证
【发布时间】:2015-01-04 13:25:29
【问题描述】:

我刚刚跟随 this article 在我的 rails 4 应用程序中实现了omniauth。

在我的用户模型中,我有两种类型的用户,即 ADMIN(由表单创建)和 MEMBER(由omniauth 创建)。我需要绕过将由omniauth 创建的会员用户的所有验证。

我知道这可以通过传递这个选项来完成:

save(validate: false)

但是采用了first_or_create方法:

  def self.from_omniauth(auth)
    # where(auth.slice(:provider, :uid)).first_or_create do |user|
    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.name = auth.info.name   # assuming the user model has a name
      user.image = auth.info.image # assuming the user model has an image
    end
  end

所以,我的问题是:如何绕过这种omniauth 案例中的所有验证?

请指教。

【问题讨论】:

    标签: ruby-on-rails validation ruby-on-rails-4 devise omniauth


    【解决方案1】:

    first_or_create 似乎没有任何选择,但您仍然有几个选择。

    您可以使用first_or_initialize 代替first_or_create,它与first_or_create 的作用相同,但不保存。然后,您将拥有一条新记录,您可以调用 save(validate: false)

    但是,如果系统中有无效的记录,例如,如果您要更新这些记录的电子邮件之一,您将不得不再次绕过验证。

    我的建议是将这个逻辑转移到验证本身:

    validate_presence_of :name, unless: -> { from_omniauth? }
    
    private
    
    def from_omniauth?
      provider && uid
    end
    

    【讨论】:

    • 谢谢,它成功了。但我不能按照 DRY 原则做到这一点,unless from_omniauth? validates :name, length: { in: 1..77} validates :keywords, length: { in: 0..50} end 我需要这样做:validates :name, unless: -> { from_omniauth? } 一个一个。所以,我很好奇如何通过一次性检查unless 条件来清理它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    相关资源
    最近更新 更多