我试图检测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

另外,我使用此样式是为了在标签中包含星号。必需:
 /* add required field asterisk */
 label.required:after {
     content: " *";
 }

如果我在标签中手动设置所需的类,则它将成功显示问题是formbuilder根本没有修改标签,并且没有显示任何标记。看起来这个文件根本没有被使用,我将它作为初始值设定项包括在内,但是事件写入一个简单的puts "I am here..."它没有显示在服务器控制台中。
我错过了什么?
谢谢你事先的回答。

最佳答案

我也有同样的问题,可能是你的rails版本。
“在Rails 4中,validations类已更改为ActiveRecord因此,用activerecord::validations::presencevalidator替换activemodel::validations::presencevalidator就可以了。”
来源:http://blog.pothoven.net/2012/10/self-marking-required-fields-in-rails.html

关于ruby-on-rails - 自动用星号标记必填字段,不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16606279/

10-09 22:01