1

我的问题如下:

我有一个表单视图,需要在提交后显示成功和失败图标。在提交之前只需要显示没有成功和失败图标的表单。

当这是以下形式时,我们可以通过多种方式做到这一点:

<%= form_for @resource do |f| %>
    <div class='<%= set_class @resource, :name %>'>
        Name: <%= f.text_field :name %>
    </div>
<% end %>

检查请求是否为 POST:

    def set_class( record, attribute )
        if request.post?
            if record.errors[attribute].any?
                return "FAILED"
            else
                return "SUCCESS"
            end
        end
        # If not submitted, we don't want a class
    end

验证后设置一个标志(我们可以request.post?在上面的解决方案中替换为record.tried_to_validate):

    class MyModel < ActiveRecord::Base

        after_validation :set_tried_to_validate

        attr_accessor :validated

        def set_validated
            @tried_to_validate = true
        end

    end

但我真的不喜欢这些解决方案..

没有内部 Rails 方法来检查验证过程是否完成?

4

2 回答 2

4

您可以先测试有效性..

@form.valid?

这将生成存储在@form 上的“错误”中的错误。要查看特定字段是否存在错误,

@form.errors[:some_field] 

在您的表格上,您可以简单地执行以下操作:

<% if @form.errors[:some_field].empty? %>
  Valid
<% end %>

只要某些字段产生错误,整个表单将是 !valid?,因此您将恢复为再次显示表单 (:new),并且您可以应该“有效”或复选标记。

于 2012-07-09T14:14:00.897 回答
0

I think you are looking for something like client side validations, if want the validation to show inline on the form. http://railscasts.com/episodes/263-client-side-validations

EDIT

If you want to capture the 3 stages, you can save in your db. New, Validate, Finished and just use callbacks to save each stage and set the default to new. (You will have the change the data type of the validated attribute to string)

after_validation update attribute to "validate"

after_save update attribute to "Finished"

Then you can use an if elsif else conditions to check for the value of that attribute and render the tick and cross. Obviously, this isn't pretty and you should just use valid? and the errors? helpers.

于 2012-07-09T14:45:17.967 回答