simple_form和hstore基本功能 [英] simple_form and hstore basic functionality

查看:95
本文介绍了simple_form和hstore基本功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can get hstore to work with simple_form but all but the most basic functionality (saving) just doesn't work. Validation messages don't show up on the individual fields... all hstore fields oddly show as required, even the values themselves don't populate correctly unless set manually.

我必须做这样的事情:

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

我必须对hstore哈希使用simple_fields_for,它可以正确保存,但是在编辑时,如果不使用input_html设置值,则不会填充值.它将每个字段都标记为必填字段,并且根本不会显示验证错误(它们确实起作用).

I have to use simple_fields_for for the hstore hash and it saves properly but on edit the values don't populate without using the input_html to set the value. It marks every field as required and validation errors don't show up at all (they do work).

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

Using hstore validations like so (added from below answer):

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

有什么想法吗?谢谢.

推荐答案

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

You can find an example of how to add some custom validations for Hstore here:

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

但是关于如何使验证与简单表单一起使用,我不确定.

But as for how to get the validations to work with Simple form, I'm not sure.

这篇关于simple_form和hstore基本功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆