简体   繁体   English

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

[英]Issue with Rails Active Record query with JSON parameters

I have a Notification model with a notification_objects parameter. 我有一个带有notification_objects参数的Notification模型。 Notification.first.notification_objects returns an array of hashes. Notification.first.notification_objects返回一个哈希数组。 I've created a @notification_objects variable that holds the an array of hashes with the same key/value pairs (except with symbols instead of strings for keys). 我创建了一个@notification_objects变量,该变量保存具有相同键/值对的散列数组(除了符号而不是键的字符串)。 How can I find this first Notification using Notification.where() ? 如何使用Notification.where()找到第一个Notification Stringifying the keys in @notification_objects did not work. 对@notification_objects中的键进行字符串化无法正常工作。 I'm using Postgres 9.4 and Rails 4.2. 我正在使用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

You could try to use .to_json instead of .as_json 您可以尝试使用.to_json而不是.as_json

Notification.where(notification_objects: @notification_objects.to_json)

.to_json returns a JSON string representing the model. .to_json返回表示模型的JSON字符串。

references: http://apidock.com/rails/ActiveRecord/Serialization/to_json 参考: http : //apidock.com/rails/ActiveRecord/Serialization/to_json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM