繁体   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