Does rails support mysql json data type

2020-08-20 11:25发布

问题:

I'm aware that in rails we can use a text data type for columns in mysql that we want to save hashes or array to it, where rails serialize the hash in yaml format and save it in the column.

class A < ActiveRecord::Base
  serialize :data, Hash
end

However if I need to perform some search on this column, I have to load all records and de-serialize all the hashes, and use ruby to search within the hashes. So is there a way to tell mysql to search within the hashes and return matched records ? I think this is not supported with normal yaml serialization as it is just a text, so does rails support mysql json data type or any other solution to this problem ?

回答1:

It looks like Rails 5 should have support for the MySQL JSON data type natively. There is a pull request here #21110 that describes it a bit.

And it looks like you'll be able to add this to your create_table or change_table:

create_table :json_data_type do |t|
    t.json :settings
end