【问题标题】:Automatically mark required fields with an asterisk, not working用星号自动标记必填字段,不起作用
【发布时间】:2014-01-07 23:35:04
【问题描述】:

我正在尝试检测 mongoid 模型中的必填字段,以便在视图中的标签后添加标记。这是我正在使用的初始化程序。请注意,与 Mongoid 唯一不同的是 Mongoid::Validations::PresenceValidator,在 ActiveRecord 中将是 ActiveModel::Validations::PresenceValidator,所以也许这不是一个与 mongoid 相关的问题(?):

class ActionView::Helpers::FormBuilder
  alias :orig_label :label

  # add a 'required' CSS class to the field label if the field is required
  def label(method, content_or_options = nil, options = nil, &block)
    if content_or_options && content_or_options.class == Hash
      options = content_or_options
    else
      content = content_or_options
    end

    if object.class.validators_on(method).map(&:class).include? Mongoid::Validations::PresenceValidator

      if options.class != Hash
        options = {:class => "required"}
      else
        options[:class] = ((options[:class] || "") + " required").split(" ").uniq.join(" ")
      end
    end

    self.orig_label(method, content, options || {}, &block)
  end
end

另外,我使用这种样式是为了在 lable.required 中包含一个星号:

 /* add required field asterisk */
 label.required:after {
     content: " *";
 }

如果我在标签中手动设置了所需的类,则显示成功。问题是 FormBuilder 根本没有修改标签,也没有显示任何标记。似乎根本没有使用该文件,我将其作为初始化程序包含在内,但写入简单 puts "I am here..." 的事件未显示在服务器控制台中。

我错过了什么?

提前感谢您的回答。

【问题讨论】:

  • 不是 ActionView::Helpers::FormHelper 吗?

标签: ruby-on-rails ruby mongoid


【解决方案1】:

我也遇到了同样的问题,可能是你的 rails 版本。

“在 Rails 4 中,验证类已更改为 ActiveRecord。因此,将 ActiveModel::Validations::PresenceValidator 替换为 ActiveRecord::Validations::PresenceValidator 应该可以解决问题。”

来源:http://blog.pothoven.net/2012/10/self-marking-required-fields-in-rails.html

【讨论】:

    【解决方案2】:

    尝试扩展

    module ActionView::Helpers::FormHelper
    

    【讨论】:

    • 感谢您的回答!我一开始还以为自己是个笨蛋,这么简单的事!但后来我发现它不起作用,它说FormHelper is not a class (TypeError)。不管怎样,我见过很多使用 FormBuilder 的例子,比如这个:gist.github.com/jordanandree/9d6812f0c99a20cacb2c
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    相关资源
    最近更新 更多