Rails 4中check_box_tag简单验证失效问题求助
解决支持表单复选框验证不生效的问题
看起来问题出在参数传递、虚拟属性定义和表单控件使用这几个环节上,咱们一步步来修正:
1. 修正模型的虚拟属性定义
你之前对虚拟属性的理解有误哦!ActiveModel 无法自动识别未定义的属性,所以必须保留attr_accessor :dataprotection,不然模型根本读不到这个参数值,验证自然不会触发。你的模型代码应该保持这样:
class Support include ActiveModel::Validations attr_accessor :dataprotection # 必须保留,模型才能访问这个虚拟属性 validates :dataprotection, acceptance: true end
2. 修正视图的表单控件
你现在用的check_box_tag生成的是顶级参数dataprotection,而控制器创建Support实例时用的是params[:support],这就导致模型接收不到复选框的值。
把视图里的复选框和标签改成 form builder 的方法,参数会自动封装到support哈希中:
= form_for :support, :url => { :action => "create" }, :html => { :method => :post } do |f| = render 'shared/error_messages_support' %div = f.check_box :dataprotection # 用form builder的check_box方法 = f.label :dataprotection, simple_format(t"support.dataprotection") # 对应form builder的label方法
3. 确认错误提示partial的正确性
确保shared/error_messages_support这个partial能正确显示@support的错误信息,比如可以参考这个写法(如果之前的partial有问题的话):
- if @support.errors.any? .alert.alert-error %h2= "#{pluralize(@support.errors.count, "error")} prohibited this support request from being sent:" %ul - @support.errors.full_messages.each do |msg| %li= msg
4. 验证效果
现在测试一下:不勾选复选框提交表单,模型会触发acceptance验证并返回错误,页面会重新渲染new动作,同时显示对应的错误提示(比如国际化翻译后的"Dataprotection must be accepted");勾选之后就能正常提交表单了。
补充说明:虽然你用了protected_attributes gem兼容旧的参数处理方式,但用form builder的方式传递参数是最稳妥的,能保证参数正确关联到模型实例。
内容的提问来源于stack exchange,提问作者user929062
相关产品推荐
相关产品推荐

