ruby-on-rails - 是否有任何库来管理 Rails 应用程序的数据库字段中的 json 内容?

标签 ruby-on-rails ruby json

我有一个 Rails 2 应用程序,用于管理表中的 json 字段。它需要:

  • 读取json
  • 将json转化为模型属性和表单字段
  • 将对表单字段的编辑保存到 json 字段中
  • 为一些 json 值添加验证
  • 适用于多种模型

目前,我有一个库文件,手动添加方法提取并保存到json中,如下所示:

module Configuration
  def configuration_json
    configuration? ? JSON.parse(self.configuration) : {}
  end

  def some_json_value
    if !self.configuration.nil? && configuration_json["parentKey"]
      configuration_json["parentKey"]["someJsonValue"]
    end
  end

  def some_json_value=(val)
    new_config = configuration_json.deep_merge({
      "FeatureConfiguration" => { "someJsonValue" => val }
    })
    self.configuration = new_config.to_json
  end

  def some_json_value_validation
    # ...
  end
end

我在模型中包含了这个

class SomeModel < ActiveRecord::Base
  include Configuration
  validate :some_json_value_validation

  # ...
end

是否有更好/DRY-er 的方法?目前,当 json 结构发生变化时,它真的很笨重,因为在 rails 应用程序中有很多步骤需要修改。

我无法更改 json 字段的用途,因为它用于配置另一个应用程序,这是 Rails 应用程序支持的主要应用程序。

最佳答案

最好的方法是制作一个 Configuration 模型,然后简单地制作一个 to_json 方法来构建正确的 json 对象。

如果你真的想解析 json 并在每次操作时将其转换回来,你可以创建一个帮助器来为你创建方法,比如 json_attr_accessor

例子:

module Configuration

  def configuration_json
    configuration.present? ? JSON.parse(configuration) : {}
  end

  module ModelExtensions

    def json_attr_accessor(*symbols)
      symbols.each do |sym|

        key = sym.to_s.camelize(:lower)

        define_method(sym) do
          ['FC', key].reduce(configuration_json) do |json, key|
            json and json[key]
          end
        end

        define_method("#{sym}=") do |val|
          hash = configuration_json.deep_merge 'FC' => { key => val }
          self.configuration = hash.to_json
        end

      end
    end

  end

  def self.included(base)
    base.extend ModelExtensions
  end

end

在模型中:

class SomeModel < ActiveRecord::Base
  include Configuration
  json_attr_accessor :some_json_value
end

这是自定义验证器的帮助链接:

http://www.perfectline.ee/blog/building-ruby-on-rails-3-custom-validators

关于ruby-on-rails - 是否有任何库来管理 Rails 应用程序的数据库字段中的 json 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15088178/

相关文章:

MySQL: ERROR 1006 (HY000) 无法创建数据库 (errno: 26469527)

ruby-on-rails - Faye 服务器日志记录

ruby-on-rails - 安装 Nokogiri gem 时出错

ruby - 如何阻止程序自行退出?

ruby-on-rails - Twilio 的未定义方法 `account'

json - 正确访问json文件

ruby-on-rails - 从 heroku slugs 中排除 gems 中的文件(使用 .slugignore、heroku)

ruby - RSpec HaveSelector 在使用 Capybara 时无法正常工作

PHP json_decode 不起作用

jquery - JSON 数据访问对象