如何验证一个属性Rails 3

时间:2011-09-16 09:52:35

标签: ruby-on-rails-3

我有一个获取用户名的表单。

如果此名称有效,我会将其发送到另一个表格,以输入他们的电子邮件,密码等。

我想仅验证名称。

有没有办法@user.name.valid?

由于

2 个答案:

答案 0 :(得分:1)

不,没有这样的方法。但是你可以写自己的:

class User < ActiveRecord::Base
  ...
  def attribute_valid?(name)
    if valid?
      true
    else
      !!self.errors[name]
    end
  end
  ...
end

虽然这基本上运行所有验证,然后检查您的具体属性是否属于坏的属性。因此,如果您正在寻找性能,这不是解决方案。

答案 1 :(得分:-1)

如果有人在此结束:I wrote a gem for that

gem 'valid_attribute', github: 'kevinbongart/valid_attribute'

假设你有:

class Product < ActiveRecord::Base
  belongs_to :company

  validates :company, presence: true
  validates :name, format: { with: /\A[a-zA-Z]+\z/ }
  validates :name, uniqueness: { scope: :company }
  validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/ }
end

这个gem让你可以独立测试每个属性的有效性:

company = Company.new
product = Product.new(company: company, name: "heyo")

# Test only one attribute:
product.valid_attribute?(:company)      # => true
product.valid_attribute?(:name)         # => true
product.valid_attribute?(:legacy_code)  # => false

# Test several attributes at once, like a boss:
product.valid_attribute?(:company, :name)               # => true
product.valid_attribute?(:company, :name, :legacy_code) # => false

# Wow, you can even filter down to a specific validator:
product.valid_attribute?(name: :format)                     # => true
product.valid_attribute?(name: [:format, :uniqueness])      # => true
product.valid_attribute?(name: :format, company: :presence) # => true