complete_morons
complete_morons

Reputation: 843

Check if integer belongs to a set of integers (IDs)

I want to check if current_user.id belongs to a set of IDs. The goal is to display records where current_user's ID belongs to a set of IDs.

IDs are saved in a t.text table_column.

For example: "2, 6, 78".

I have attempted to do this:

array = table_column.split(", ").map(&:to_i)

array.include?(current_user.id)

then you would get an array and use include? to check if ID is included in array. But how to use that in controller to filter records?

this should be displayed in controller

@records = Record.where(.../* display if current_user.id >> table_column IDs */)

Upvotes: 0

Views: 133

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

I would strongly encourage you to change your database structure to better handle this, but if you can't, then this should work. Makes me feel dirty writing it, but it will work.

Record.where(['table_column = ? OR table_column LIKE ? OR table_column LIKE ? OR table_column LIKE ?',
              "#{id}", "#{id},%", "%, #{id},%", "%, #{id}"])

Before you do that though look at your database and see if they have more efficient regular expression queries. I know PostgreSQL has some.

Upvotes: 1

Related Questions