簡體   English   中英

驗證attr_accessor,Rails 4

[英]Validating attr_accessor, Rails 4

無論出於何種原因,我無法正確驗證我的attr_accessor屬性。

  attr_accessor :line1, :city, :postal_code, :state, :personal_id_number, :ssn_last_4, :bank_account_number, :bank_routing_number

  validates :line1, presence: true, if: :line1
  validates :city, presence: true, if: :city
  validates :postal_code, presence: true, length: { maximum: 10 }, if: :postal_code
  validates :state, presence: true, length: { maximum: 2 }, if: :state
  validates :personal_id_number, presence: true, numericality: { only_integer: true }, if: :personal_id_number
  validates :ssn_last_4, presence: true, length: { is: 4 }, numericality: { only_integer: true }, if: :ssn_last_4
  validates :bank_account_number, numericality: { only_integer: true }, if: :bank_account_number
  validates :bank_routing_number, numericality: { only_integer: true }, if: :bank_routing_number

使用此代碼,所有屬性都會通過驗證是否應該進行驗證。 例如, postal_code甚至會傳遞超過10個字符,而其他字符甚至會在空白時傳遞。

如果我刪除if語句,它們都沒有通過。 我得到了每一個錯誤。 例如,正確填寫表格將顯示city不能為空等...

if語句需要存在,因為這些屬性在創建時將為空,並且僅出現在edit表單中。

如何獲得與attr_accessor一起使用的attr_accessor

如果類沒有由數據庫表備份,則可以使用ActiveModel獲取ActiveRecord功能。 您需要做的就是在您的班級中包含該模型。 然后驗證將按照您對ActiveRecord的預期運行,並且您不需要條件。

class Foo
  include ActiveModel::Model
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM