唯一性验证器返回未定义的方法`new_record?'

时间:2017-08-03 13:00:11

标签: ruby-on-rails validation

我的表单对象有问题,如果用户名验证唯一性,然后我搜索了如何在表单对象中使用唯一性验证的答案,那么我在这个问题中找到答案

on an ActiveModel Object, how do I check uniqueness?

但不幸的是,在我创建了UniquenessValidator类之后,它在表单视图中返回错误,

undefined method `new_record?' for #<UserForm:0x007fd40c42d258>

如何解决此错误,我正在使用Rails 5.1

UserForm(user_form.rb):

class UserForm
  include Virtus.model

  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attribute :username, String
  attribute :password, String
  attribute :company_name, String

  validates :username, presence: { message: '%{attribute} is required'}
  validates :password, presence: { message: '%{attribute} is required'}
  validates :company_name, presence: { message: '%{attribute} is required'}
  validates :password, length: { minimum: 6, message: '%{attribute} must me
                                             minimum of 6 characters' }
  validates :username, uniqueness: { case_sensitive: false, model: User, attribute: :username }

  def persisted?
    false
  end

  def save
    if valid?
      persist!
      true
    else
      false
    end
  end

  private

  def persist!
    @company = Company.create!(name: company_name)
    @company.users.create!(username: username, password: password,
                           user_type: 'Owner')
  end
end

1 个答案:

答案 0 :(得分:1)

new_record?方法来自ActiveRecord :: Persistence模块。我怀疑你可以简单地包含它,因为你的模型不是ActiveRecord :: Base的典型子类。

这是一个快速而肮脏的解决方案,可以满足您的需求:

validates :username, if: :new_username?

# ...

private

def new_username?
    User.where(username: username).empty?
end

请注意,只有在您创建新用户时,此功能才能正常运行。更新现有用户将始终失败。 (根据您发布的代码,无论如何,看起来就是您使用此模型的方式。)