store_accessor没有保存在postgresql中

时间:2014-05-20 08:26:15

标签: ruby-on-rails ruby postgresql ruby-on-rails-4 hstore

我在数据库中有以下表格

+----+-------------+------------+
| 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方法应该将键值对合并到原始哈希中,但它们似乎并非如此。如何让它们合并到新数据中?

1 个答案:

答案 0 :(得分:2)

我不确定它是否是rails hstore实现中的错误或功能。 ActiveRecord无法识别hstore属性已更改且未保存。所以你必须强制执行它。

book = Book.find(1)
book.pages = "453"
book.data_will_change!
book.save

book.data_will_change!强制执行数据属性保存。