简体   繁体   中英

Mysql 5.7 json datatype, query with activerecord in Rails 5

I am making an application with Rails 5 rc1. Rails 5 support mysql 5.7 json datatype.

add_column :organizations, :external, :json

Suppose the value in this column is as follows:

+---------------------------+
| external                  |
+---------------------------+
| {"id": 10, "type": "mos"} |
+---------------------------+

To search a particular "id" and "type" in external column, I use the following query in mysql:

select external from organizations where JSON_CONTAINS(external,'{"id": 10, "type": "mos"}') ;

Now, I want to know, how to make the same query using rails. The following doesn't work:

Organization.where("JSON_CONTAINS(external,'{"id": 10, "type": "mos"}')")

Note: I cannot remove quotes around the json text as it is part of the query.

您仍然可以利用ActiveRecord的where方法和绑定变量,而无需使用find_by_sql。

Organization.where("external->'$.id' = :id and external->'$.type' = :type", id: 10, type: "mos")

With MYSQL you can use JSON_EXTRACT to pull values from a JSON object stored in a field. In your case, try using...

Organization.where("JSON_EXTRACT(external, '$.id') = 10 AND JSON_EXTRACT(external, '$.type') = 'mos'")

and just for kicks, in pseudo code...

<Class>.where("JSON_EXTRACT(<column_header>, '$.<object key>') <comparison operator> <object value>")

This should get the job done, although there may be a prettier way to write it :)

I did not find any solution through activerecord as of now. An alternative way to query is as follows:

type = "mos"
id = 10

organization = Organization.find_by_sql(["select * from organizations where JSON_CONTAINS(external_ref ,'{\"id\": ?, \"type\": \"#{ActiveRecord::Base::sanitize(type).remove("'")}\"}')", id]).first

Once there is a solution with activerecord query interface, I will update.

Like this:

id_field = '$."id"'
type_field = '$."type"'    
Organization.where("JSON_UNQUOTE(json_extract(external, '#{id_field}')) = ? AND JSON_UNQUOTE(json_extract(external, '#{type_field}')) = ?", 10, "mos")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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