带有JSON参数的Rails Active Record查询问题

时间:2015-12-16 21:46:19

标签: ruby-on-rails json activerecord

我的Notification模型带有notification_objects参数。 Notification.first.notification_objects返回一个哈希数组。我创建了一个@notification_objects变量,用于保存具有相同键/值对的哈希数组(除了符号而不是键的字符串)。如何使用Notification找到第一个Notification.where()?在@notification_objects中对字符串进行字符串化不起作用。我正在使用Postgres 9.4和Rails 4.2。

[18] pry(main)> Notification.first.notification_objects
=> [{"class_name"=>"Ad", "ar_object_id"=>1}]

[19] pry(main)> @notification_objects
=> [{:class_name=>"Ad", :ar_object_id=>1}]


# both as_json and to_json do not work here:
[20] pry(main)> Notification.where(notification_objects: @notification_objects.as_json)
=> []

[21] pry(main)> @notification_objects.as_json
=> [{"class_name"=>"Ad", "ar_object_id"=>1}]

[22] pry(main)> Notification.first.notification_objects.as_json == @notification_objects.as_json
=> true

1 个答案:

答案 0 :(得分:0)

您可以尝试使用.to_json代替.as_json

Notification.where(notification_objects: @notification_objects.to_json)

.to_json返回表示模型的JSON字符串。

的引用: http://apidock.com/rails/ActiveRecord/Serialization/to_json