2011-09-16 74 views
0

我有一个获取用户名的表单。如何验证一个属性Rails 3

如果此名称是有效的,那么我送他们到另一种形式在他们的电子邮件,密码等

进入我只想验证名称。

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

感谢

回答

1

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

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

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

+0

我想那也许只是使用jQuery和验证客户端侧。它只是一个名称的领域,所以可能是更好更容易的解决方案,尤其是性能明智。 – chell

+0

是!!意思不是吗? – chell

+0

我认为客户端验证可能是一个好主意(如果它满足您的安全/完整性需求)。 !!!运算符只是双倍!这个操作符的确意味着“不”。我使用它不会收到错误信息,但只有'true' – moritz

-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 

这种宝石让你测试的每个independentely属性的有效性:

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 
+2

这里最好提供这些步骤,并使用链接作为参考以获取更多详细信息。这样,一旦链接失效,您的答案不会失去它可能拥有的全部价值。 – Anthon