Rails在TEXT列上添加3个破折号的插入和更新前缀

时间:2014-12-26 17:52:52

标签: mysql ruby-on-rails

我试图弄清楚为什么Rails 4在MySQL TEXT字段的所有插入和更新前加---。一切正常,但我只是好奇为什么它在那里。

数据是一个简单的JSON字符串。没什么特别的。

这是更新数据库的ruby代码:

data = {'branches' => [], 'tags' => []}
//
// Some code here to populate data['branches'] and data['tags']
//
component = Component.find(params[:id])
component.available_tags = data.to_json
component.save

puts data.to_json产生以下输出:

{"branches":["develop","master","release-2014-12-15"],"tags":["release-2014-12-11","release-2014-12-10","release-2014-11-24.01","release-2014-11-24","release-2014-10-22","release-2014-10-09"]}

但由于某种原因,这会产生以下UPDATE查询:

UPDATE `components` SET `available_tags` = '--- \'{\"branches\":[\"develop\",\"master\",\"release-2014-12-15\"],\"tags\":[\"release-2014-12-11\",\"release-2014-12-10\",\"release-2014-11-24.01\",\"release-2014-11-24\",\"release-2014-10-22\",\"release-2014-10-09\"]}\'\n', `updated_at` = '2014-12-26 17:28:11' WHERE `components`.`id` = 10

我有另一个包含TEXT字段的表格,它还有---

这是表格的样子:

mysql> desc components;
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| id             | int(11)      | NO   | PRI | NULL    | auto_increment |
| component_name | varchar(255) | YES  |     |         |                |
| repo_url       | varchar(255) | YES  |     |         |                |
| available_tags | text         | YES  |     | NULL    |                |
| created_at     | datetime     | YES  |     | NULL    |                |
| updated_at     | datetime     | YES  |     | NULL    |                |
| repo_type      | varchar(255) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

1 个答案:

答案 0 :(得分:0)

这是因为在保存到数据库之前,对象使用YAML格式获取serialized。如果您只想存储纯文本,请使用:

component.available_tags = data.to_json.to_s

但是,如果您只想在该列中存储JSON,可以将其添加到模型中:

serialize :available_tags, JSON

这样,您的:available_tags列将自动序列化/反序列化,因此您无需运行JSON.parsedata.to_json即可直接作为JSON对象访问该字段

例如:

component = Component.first
component.available_tags = data # no need to use to_json, will automatically be converted
component.save

component = Component.first
json_object = component.available_tags  # Will return a JSON object