Rails客户端验证不适用于简单的表单关联

时间:2012-12-29 14:31:57

标签: ruby-on-rails ruby simple-form client-side-validation

我有一个模型用户

class User < ActiveRecord::Base
  validates :goal, :presence => true, :on => :update
  belongs_to :goal, :class_name => Goal, :foreign_key => "goal_id"
  ...
end

并在表格上

<%= simple_form_for @users,:remote => true, :url => registration_path(resource_name), :html => { :method => :put, :multipart => true }, :validate => true do |f| %>
 <%= f.association :goal,:label => "My overall goal is clearing", :input_html => {:class => 'goals'},:include_blank => true %>

但是rails客户端验证没有获得关联的验证,它让我填写空白目标。

rails客户端验证gem是否适用于简单的表单关联?

我在html页面上获得以下脚本

if (window.ClientSideValidations == undefined) window.ClientSideValidations = {};
if (window.ClientSideValidations.forms == undefined) window.ClientSideValidations.forms = {};
window.ClientSideValidations.forms['edit_user_14'] = {
    "type": "SimpleForm::FormBuilder",
    "error_class": "error",
    "error_tag": "span",
    "wrapper_error_class": "field_with_errors",
    "wrapper_tag": "div",
    "wrapper_class": "input",
    "wrapper": "default",
    "validators": {
        "user[mobile_number]": {
            "format": [{
                "message": "should be 10 digits",
                "with": /^\d{10}$/i
            }]
        },
        "user[profile_pic]": {
            "integrity": [{
                "message": "translation missing: en.activerecord.errors.models.user.attributes.profile_pic.integrity"
            }],
            "processing": [{
                "message": "translation missing: en.activerecord.errors.models.user.attributes.profile_pic.processing"
            }],
            "download": [{
                "message": "translation missing: en.activerecord.errors.models.user.attributes.profile_pic.download"
            }],
            "format": [{
                "message": "Wrong file format",
                "with": /\.(gif|jpeg|jpg|png)$/i,
                "allow_blank": true
            }]
        }
    }
};

2 个答案:

答案 0 :(得分:1)

这里的关键区别是使用validates :goal_id ...而不是validates :goal ...

由于这是一个关联,因此ActiveRecord模型(以及底层数据存储)中的不动产是goal_id。这是client_side_validations默认寻找的内容。

答案 1 :(得分:0)

看起来ClientSideLavodation gem无法找到关联的正确验证,所以只需添加

即可
validates :goal_id, :presence => true, :on => :update

到你的模特。