我在数据库中有以下表格
+----+-------------+------------+
| id | name | data |
+----+-------------+------------+
| 1 | string | hstore |
+----+-------------+------------+
使用以下模型
class Book < ActiveRecord::Base
store_accessor :data, :author, :pages
end
但是,当我运行以下命令时,store_accessor生成的write方法不会保存到数据库中:
> 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方法应该将键值对合并到原始哈希中,但它们似乎并非如此。如何让它们合并到新数据中?
答案 0 :(得分:2)
我不确定它是否是rails hstore实现中的错误或功能。 ActiveRecord无法识别hstore属性已更改且未保存。所以你必须强制执行它。
book = Book.find(1)
book.pages = "453"
book.data_will_change!
book.save
book.data_will_change!
强制执行数据属性保存。