2014-11-20 36 views
0

我正在尋找一種僅在一個屬性上使用ActiveRecord::Base#valid?的方法。請看下面的例子,通過RailsGuides啓發:使用ActiveRecord :: Base#valid驗證只有一個屬性?

class Product < ActiveRecord::Base 
    belongs_to :company 

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

調用Product#valid?將觸發因爲name驗證的SQL查詢:

Product.new(legacy_code: "helloworld", company: c).valid? 
    Product Exists (0.3ms) SELECT 1 AS one FROM "products" WHERE ("products"."name" IS NULL AND "products"."company_id" = 1) LIMIT 1 
=> true 

現在,我只希望驗證legacy_code屬性:

Product.new(legacy_code: "helloworld").valid? 
    Product Exists (0.2ms) SELECT 1 AS one FROM "products" WHERE ("products"."name" IS NULL AND "products"."company_id" IS NULL) LIMIT 1 
=> true 

看到問題了嗎?我喜歡使用類似Product#valid?(:legacy_code)的東西,並避免試圖驗證我不關心的屬性的查詢。

到目前爲止,我的解決方案是使用我可以獨立調用的Product#valid_legacy_code?方法,並在我的模型的驗證聲明中調用此方法。

回答

4

我最後寫一個寶石爲:https://github.com/KevinBongart/valid_attribute

# 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 
+1

感謝酷的寶石! – 2015-04-20 18:24:05

相關問題