How do I create a query that I search for when the input value is an array in Rails Active record?

Asked 2 years ago, Updated 2 years ago, 122 views

As the title suggests, when importing a value from DB, the input value is an array.

Unfortunately, it would be nice if the DB column corresponds 1:1 with each value in the array, but it is not.

In DB,

[..., A021, A502, A4152, B051, B202, C075, D252, .... ]

It's inside like this.

Arrays entering input values are

[A, B, C ... ]

It's going in like this.

So I want to get the result that I want when the input value is included in the corresponding column and matches the part

Datas.where('code LIKE ?', array)
Datas.where('code LIKE ?', '%#{array}%')
Datas.where('code LIKE IN ?', array) # error

I wrote the code in rails like this, but this does not release the array in SQL

SELECT * FROM ... WHERE code LIKE "['A', 'B']"

This is how the query went in

I'm still trying various things, but if it doesn't work, I'm thinking about separating that column into codes and numbers

I think you can LIKE it one by one in SQL, but I think it's against Ruby's spirit and there must be a comfortable way.

Is there a simple way to solve it with an active record query?

ruby-on-rails array querying active-record

2022-09-21 16:16

1 Answers

There are two ways.

(1) Detach the table

A method of separating the values of an array into different tables. For example, suppose that the table now is the player of the game and the item you have, and think of it as the following table.

In this state, you can assume that you want to find a player with a knife/shield/ring.

Make a separate player_items table

It would be better to save it as above.

(2) taggable-array

The other way is to use the array column. If you use Postgresql, You can use the gem act-as-tagable-array-on.

When the column saved as an array is named items,

class Player < ActiveRecord::Base
  acts_as_taggable_array_on :items
end

If you write it down like above,

Player.with_any_items (["knife"",shield"])

You can read the Players by doing this. However, the information called knife and 021 needs to be in two separate array columns to be used.


2022-09-21 16:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.