簡體   English   中英

實現動態表單驗證Rails的最佳方法

[英]Best way to implement dynamic form validation Rails

我有兩個<select>框和一個文本輸入。

第一個<select>是父級,第二個<select>是子級。 子級由父級通過JQuery更新。

文本輸入中允許的值將取決於<select>框的值。 在某些情況下,它需要是INT,在其他情況下則是布爾值。 在某些情況下,是關聯記錄的<select>

使用Rails 4和Activerecord關聯與驗證的最佳方法是什么?

您可以在模型中實現以下自定義驗證:

validate :custom_validation

private
def custom_validation
  case params[:select_field_1]
  when 'foo'
    record.errors.add(:select_field_2, 'must be an integer') unless select_field_2.is_a?(Integer)
  when 'bar'
    record.errors.add(:select_field_2, 'must be a boolean') unless select_field_2.is_a?(Boolean)
  when 'baz'
    record.errors.add(:select_field_2, 'must exist') unless Model.exist?(select_field_2)
  end
end

是否選擇轉換類型取決於select_field_2模型和視圖。 您可能會遇到select_field_2總是返回字符串的問題。 在那種情況下,您將需要更多的方法來檢查該屬性的值是否充當整數或布爾值。

請參閱: http : //guides.rubyonrails.org/active_record_validations.html#custom-methods

暫無
暫無

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

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