实现动态表单验证Rails的最佳方法

时间:2015-01-26 08:54:10

标签: javascript jquery ruby-on-rails ruby ruby-on-rails-4

我有两个<select>框和一个文本输入。

第一个<select>是父级,第二个<select>是孩子。孩子通过JQuery由父母更新。

文本输入中允许的值取决于<select>框的值。在某些情况下,它需要是一个INT,在另一个布尔值中。在某些情况下还有<select>个关联记录。

使用Rails 4和Activerecord关联和验证实现此目的的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以在模型中实现这样的自定义验证:

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