[英]Best way to implement dynamic form validation Rails
I have two <select>
boxes and a text input. 我有两个
<select>
框和一个文本输入。
The first <select>
is the parent and the second <select>
is the child. 第一个
<select>
是父级,第二个<select>
是子级。 The child gets updated by the parent via JQuery. 子级由父级通过JQuery更新。
The values that are allowed in the text input will be dependent on the value of the <select>
boxes. 文本输入中允许的值将取决于
<select>
框的值。 In some cases it needs to be an INT, in other a boolean. 在某些情况下,它需要是INT,在其他情况下则是布尔值。 And in some cases a
<select>
of associative records. 在某些情况下,是关联记录的
<select>
。
What is the best way to achieve this using Rails 4 and Activerecord Associations and Validation? 使用Rails 4和Activerecord关联与验证的最佳方法是什么?
You can implement a custom validation like this in your model: 您可以在模型中实现以下自定义验证:
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
It depends on your models and views if select_field_2
is typecasted or not. 是否选择转换类型取决于
select_field_2
模型和视图。 You might run into the problem that select_field_2
always returns strings. 您可能会遇到
select_field_2
总是返回字符串的问题。 In that case you will need more methods to check if the value of that attribute acts like a integer or boolean. 在那种情况下,您将需要更多的方法来检查该属性的值是否充当整数或布尔值。
See: http://guides.rubyonrails.org/active_record_validations.html#custom-methods 请参阅: http : //guides.rubyonrails.org/active_record_validations.html#custom-methods
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.