【问题标题】:Programmatically creating User with devise and first_or_create使用 devise 和 first_or_create 以编程方式创建用户
【发布时间】:2015-07-29 06:25:46
【问题描述】:

我必须通过 api 以编程方式创建用户——我能够创建传递正确参数的用户,即:

x={"email"=>"kid@kid.com", "username"=>"levi", "password"=>"password","password_confirmation" => "password", "firstname"=>"Bob", "lastname"=>"Smith"}
u=User.new(x)
u.valid?

并且能够在保存之前检查这是否是一个有效的用户,等等。但问题是,如果其他用户的用户名或电子邮件等参数已经存在,我会在保存时收到错误。

现在我可以检查用户是否已经存在(即u=User.where(username: x['username'])u=User.where(email: x['email'])——这可能就足够了,但我想知道是否有办法使用u=User.where(x).first_or_create with devise?一般适用于其他模型,但不能设计。

【问题讨论】:

  • 在 Devise 中使用 find_or_create 有什么问题?
  • 如果您对电子邮件和用户名进行唯一性验证,.valid? 将实际检查数据库以查看该值是否存在。也许如果您添加更多关于您要实现的目标的详细信息,我们可以为您指明正确的方向。您是尝试从控制器还是种子文件执行此操作?

标签: ruby-on-rails ruby-on-rails-4 devise activemodel


【解决方案1】:

find_or_create_by (http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by) 的问题在于,它会尝试找到与您作为条件传入的所有属性相匹配的用户。这很少是一种有用的方法。相反,将其包装在您的模型中:

class User < ActiveRecord::Base
  def self.username_find_or_create(attributes = {})
    User.create(attributes) unless User.exists?(attributes.slice(:username, :email))
  end
end

Exists 比哪里快)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多