【问题标题】:Rails 3 validates_uniquess_of virtual field with scopeRails 3 validates_uniquess_of 具有范围的虚拟字段
【发布时间】:2012-07-31 01:23:54
【问题描述】:

我正在开发一个 Rails 3 应用程序,该应用程序需要在虚拟字段上运行验证以查看记录是否已存在...这是我的模型代码:

      #mass-assignment
      attr_accessible :first_name, :last_name, :dob, :gender

      #validations
      validates_presence_of :first_name, :last_name, :gender, :dob
      validates :fullname, :uniqueness => { :scope => [:dob] }

def fullname
    "#{first_name} #{last_name}"
  end

我没有收到任何错误,它通过了验证。

【问题讨论】:

    标签: ruby-on-rails-3 virtual-attribute validates-uniqueness-of


    【解决方案1】:

    我认为你不能用标准的validates 做类似的事情。原因是,它通常是一个“简单”的 sql 查找唯一性。但是要检查从您的方法返回的内容的唯一性,它必须:

    • 获取范围内的所有条目
    • 对于每个,执行fullname 方法。
    • 在测试唯一性时将每个结果添加到数组中

    当数据集很小时很简单,但是一旦您的范围内达到 10K 以上匹配项,就需要很长时间。

    我个人会使用 dob 范围使用标准 before_save 来执行此操作

    before_save :check_full_name_uniqueness
    
    def check_full_name_uniqueness
      query_id = id || 0
      return !Patient.where("first_name = ? and last_name = ? and dob = ? and id != ?", first_name, last_name, dob, query_id).exists?
    end
    

    添加错误信息(返回前):

    errors.add(:fullname, 'Your error')
    

    回到控制器,得到错误:

    your_object.errors.each do |k, v| #k is the key of the hash, here fullname, and v the error message
      #Do whatever you have to do
    end
    

    【讨论】:

    • 这是我要做的工作:return !Patient.where(:first_name => first_name, :last_name => last_name, :dob => dob).exists?... 但是如何添加自定义错误消息?
    • 非常感谢!所以这是我遇到的一件事......它适用于创建,但它在更新时出错......
    • 当我说出错时,我的意思是它抛出了我创建的自定义错误。
    • 好的再次编辑...第二次,您的对象实际上存在并且在数据库中。因此,当然如果我们不排除它自己的 ID,条件将永远为真
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多