simple_form和hstore基本功能

时间:2013-07-08 09:23:54

标签: ruby-on-rails simple-form ruby-on-rails-4 form-for hstore

我可以让hstore使用simple_form但除了最基本的功能(保存)之外的所有功能都不起作用。验证消息不会显示在各个字段上...所有hstore字段都会根据需要奇怪地显示,即使值本身也不能正确填充,除非手动设置。

我必须做这样的事情:

<%= f.simple_fields_for :phones do |phone| %>
    <%= phone.input :agent, :input_html => { :value => @artist.phones['agent'] } %>
<% end %>

我必须使用simple_fields_for作为hstore哈希,并且它会正确保存,但在编辑时,如果不使用input_html设置值,则不会填充值。它根据需要标记每个字段,并且根本不显示验证错误(它们确实有效)。

使用像这样的hstore验证(从下面的答案中添加):

validates_hstore :emails do
  validates_format_of [:agent,:artist], :with => /@/, :allow_blank => true
end

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:1)

您可以在此处找到如何为Hstore添加一些自定义验证的示例:

https://gist.github.com/rf-/2322543

module HstoreValidation
  def validates_hstore(field, &block)
    validation_class = Class.new do
      include ActiveModel::Validations

      def self.name
        '(validations)'
      end

      def initialize(data)
        @data = data
      end

      def read_attribute_for_validation(attr_name)
        @data[attr_name]
      end
    end
    validation_class.class_eval &block

    validate do
      validator = validation_class.new(self[field])

      if validator.invalid?
        validator.errors.each do |attr, text|
          self.errors.add(attr, text)
        end
      end
    end
  end
end

但至于如何使用Simple表单进行验证,我不确定。