Hello everybody, is @ ryosk7.
I will enter from the main subject quickly.
Mysql2::Error: Operand should contain 1 column(s)
What to do if you get an error like this.
As for the situation,
user_ids = @current_user.sample_contents.pluck(:to_user_id)
@samples = SampleModel.where('
(user_id = ? and status = ?) or (user_id = ? and status is not null)',
user_ids, SampleModel.statuses[:open], @current_user.id)
.order(id: "DESC")
It was output when I wrote such code.
it's here.
user_ids = @current_user.sample_contents.pluck(:to_user_id)
@samples = SampleModel.where('
(user_id = ? and status = ?) or (user_id = ? and status is not null)',
user_ids.join(","), SampleModel.statuses[:open], @current_user.id)
.order(id: "DESC")
Did you notice the difference?
The array is changed to a string concatenated with commas.
user_ids.join(",")
If you use Active Record, it will be recognized without any problem even if you pass it as an array to user_id. The cause was that I was doing the same on SQL. If it's a single value, it's okay, but if it's multiple values, you need to pass a list of strings.
Actually, SQL is created like this. The place converted by join is the same. I'm not strong in SQL, so I learned a lot.
SELECT `sample_models`.* FROM `sample_models` WHERE ((user_id = '10,23,55' and status = 0) or (user_id = 14 and status is not null)) ORDER BY `sample_models`.`id` DESC
In the reference article, I'm hitting a query using IN. If you write in the same way,
user_ids = @current_user.sample_contents.pluck(:to_user_id)
@samples = SampleModel.where('
(user_id in (?) and status = ?) or (user_id = ? and status is not null)',
user_ids.join(","), SampleModel.statuses[:open], @current_user.id)
.order(id: "DESC")
It looks like this.
SQL is also created with IN.
SELECT `sample_models`.* FROM `sample_models` WHERE ((user_id in ('10,23,55') and status = 0) or (user_id = 14 and status is not null)) ORDER BY `sample_models`.`id` DESC
Both give the same result.
https://stackoverflow.com/questions/10012695/sql-statement-using-where-clause-with-multiple-values