如何在表单 textarea 中编辑序列化的哈希列 [英] How to edit a serialized hash column in form textarea

查看:55
本文介绍了如何在表单 textarea 中编辑序列化的哈希列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在公司模型中有一个序列化列:

I have a serialized column in Company model:

class Company < ActiveRecord::Base
  serialize :names

理想情况下,我希望它在数据库中存储这样的不同名称:

Ideally I want it to store different names like this in the database:

---
short: bestbuy
long: bestbuy ltd.

目前在我的 company#edit 页面中,我有一个文本区域:

Currently in my company#edit page, I have a text area for it:

<%= f.text_area :names %>

如果我在数据库中有那个 YAML,它将在浏览器中显示为:

If I have that YAML in the database, it will be displayed in the browser as:

{"short"=>"bestbuy", "long"=>"bestbuy ltd."}

但是当我提交它时,在数据库中它变成了:

However when I submit it, in the database it became:

--- ! '{"short"=>"bestbuy", "long"=>"bestbuy ltd."}'

问题

如何让 textarea 显示 YAML 以供编辑者编辑?

How can I make it so that textarea displays YAML for editors to edit?

如何让数据库保存正确的 YAML,而不是 YAML 和 ruby​​ 哈希的混合?

How to make the database save the proper YAML, not a mash of YAML and ruby hash?

更新

如果我将列强制设为 Hash 类型,如下所示:

If I force the column to be of type Hash like this:

serialize :names, Hash

尝试保存时会出错:

ActiveRecord::SerializationTypeMismatch in Admin::CompaniesController#update
属性应该是一个哈希值,但它是一个字符串

推荐答案

我自己的问题的一个迟到的答案:

A late answer to my own question:

class ConfigSerializer
  def self.load(i)
    if i.blank?
      {}
    else
      YAML.load(i)
    end
  end

  def self.dump(i)
    i = {} if i.blank?

    if i.is_a?(String) # Allow assigning an YAML string as input 
      i
    else
      YAML.dump(i)
    end
  end
end

在模型中

serialize :names, ConfigSerializer

这样我就可以分配一个 YAML 字符串,它会按原样存储到数据库中.只有当它从数据库加载时才转换为哈希对象.

This way I can assign a YAML string and it will be stored into the database as is. Only when it is loaded from database it is converted to hash object.

在视图中,我将 textarea 设置为具有原始 YAML 字符串,以便用户可以对其进行编辑.

In view I set textarea to have the raw YAML string, so user can edit it.

这篇关于如何在表单 textarea 中编辑序列化的哈希列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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