gpt4 book ai didi

ruby-on-rails - rails 4.1 通过 hstore 验证任意字段

转载 作者:行者123 更新时间:2023-11-29 11:11:47 25 4
gpt4 key购买 nike

我在 Rails 4.1 中使用 HStore 来管理 I18n 和语言存储。它工作得很好,我唯一的问题是我想做这样的事情(而不是使用 store_accessor)

在 Rails 4.0 中这很有效:

https://gist.github.com/rf-/2322543 ( simple_form and hstore basic functionality )

所以我可以简单地做一些事情:

  validates_hstore :content do
validates_presence_of :en
end

奇迹发生的地方(在 Rails 4.1 中似乎无法正常工作)

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

相反,我总是得到,即使该字段不为空:

messages:
:en:
- can't be blank

最佳答案

发生这种情况是因为 hstore 键/值被转换为字符串,并且当验证尝试验证属性 :en 时,它始终为 nil,因此您可以替换您的 read_attribute_for_validation 方法:

def read_attribute_for_validation(attr_name)
@data[attr_name.to_s]
end

注意:attr_name.to_s



你也可以像这样使用store_accessor:

store_accessor :content, :en

validates :en, presence: true

关于ruby-on-rails - rails 4.1 通过 hstore 验证任意字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25783538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com