在此示例中,我尝试获取由特定类型的用户创建的锻炼集合(锻炼属于特定用户,具有列名称 user_id):current_user、专业用户(继承来自用户)和管理员。这是我现在拥有的:
Workout.where('(user_id= ?) OR (user_id= ?) OR (user_id= ?)', current_user.id, User.select(&:professional?), User.find_by_admin(true).id)
我相信第二项抛出此错误:
Mysql2::Error: Operand should contain 1 column(s): SELECT
workouts
.* FROMworkouts
WHERE ((user_id= 29) OR (user_id= 2,5,29) OR (user_id= 2)) ActiveRecord::StatementInvalid: Mysql2::Error: Operand should contain 1 column(s): SELECTworkouts
.* FROMworkouts
WHERE ((user_id= 29) OR (user_id= 2,5,29) OR (user_id= 2))
如果是这种情况,我如何迭代 user_id=2,5,29(.each 除外)并提取由该特定用户组创建的所有锻炼?
最佳答案
尝试这个 where
查询,它将在 id 数组中查找 user_id
匹配
Workout.where(user_id: [current_user.id, User.select(&:professional?), User.find_by_admin(true).id].flatten)
Sql 等价
从锻炼中选择 * WHERE user_id IN (1,3,6,4,2)
关于mysql - 从belongs_to表获取Ruby中的对象集合时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28970884/