【发布时间】:2014-07-08 09:48:13
【问题描述】:
我在数据库中有下表
+----+-------------+------------+
| id | name | data |
+----+-------------+------------+
| 1 | string | hstore |
+----+-------------+------------+
以下型号
class Book < ActiveRecord::Base
store_accessor :data, :author, :pages
end
但是,当我运行以下命令时,从 store_accessor 生成的写入方法不会保存到数据库中:
> Book.create name: "Catch-22", author: "Joseph Heller"
(0.1ms) BEGIN
(1.6ms) COMMIT
+----+-------------+-----------------------------+
| id | name | data |
+----+-------------+-----------------------------+
| 1 | Catch-22 | {"author": "Joseph Heller"} |
+----+-------------+-----------------------------+
> book = Book.find(1)
(0.1ms) BEGIN
(0.1ms) COMMIT
+----+-------------+-----------------------------+
| id | name | data |
+----+-------------+-----------------------------+
| 1 | Catch-22 | {"author": "Joseph Heller"} |
+----+-------------+-----------------------------+
> book.pages = "453"
"453"
> book.save
(0.1ms) BEGIN
(0.1ms) COMMIT
true
> book
+----+-------------+-----------------------------+
| id | name | data |
+----+-------------+-----------------------------+
| 1 | Catch-22 | {"author": "Joseph Heller"} |
+----+-------------+-----------------------------+
> book.pages
nil
据我了解,store_accessor 生成的 setter 方法应该将键值对合并到原始哈希中,但似乎并非如此。如何让它们合并到新数据中?
【问题讨论】:
-
什么是
store_accessor?是某种attr_accessor吗? -
@Pavan api.rubyonrails.org/classes/ActiveRecord/Store.html 类似于 hstore 变量的 attr_accessor
-
@Pavan 不用担心,尽管页面上的示例似乎并不常见。 mikecoutermarsh.com/using-hstore-with-rails-4 似乎是事实上的称呼
标签: ruby-on-rails ruby postgresql ruby-on-rails-4 hstore