How to query array column from mysql in Rails 5.2?

前端 未结 2 1130
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 23:47

I am using gem rails~> 5.2 and gem mysql2 >= 0.3.13, < 0.5.

I have a model Lawer, which has an array column lawer_f

2条回答
  •  执笔经年
    2021-01-28 00:21

    MySQL, unlike PostgreSQL, does not support arrays in database. Therefore you needed to add this line:

    serialize :lawer_field, Array
    

    This means that you have a string field in your database, but whenever ActiveRecord is unpacking results returned by the database, it maps them directly to an instance of Ruby Array. What this means is that your only option to filter the results in the database is with any MySQL string comparison functions, LIKE, etc.

    Your options are to either use LIKE or perform some other String functions (which will not perform well as you will be unable to use indices) or build another table, add a has_many association to it and use MySQL the way it was supposed to be used. You could also, of course, migrate to PostgreSQL, but that seems to be the most extreme option.

    EDIT: you could also consider using MySQL`s JSON, which has been added recently. That depends on your version of MySQL though.

提交回复
热议问题