[英]Error getting a collection of objects in Ruby from a belongs_to table
In this example, I'm trying to get a collection of Workouts that have been created by specific types of users (a Workout belongs to a specific User, has column name user_id): either the current_user, a Professional user (inherits from User), and an admin. 在此示例中,我试图获取由特定类型的用户(锻炼属于特定用户,列名称为user_id)创建的锻炼的集合:current_user,Professional用户(继承自User)和一位管理员。 Here is what I have right now: 这是我现在所拥有的:
Workout.where('(user_id= ?) OR (user_id= ?) OR (user_id= ?)', current_user.id, User.select(&:professional?), User.find_by_admin(true).id)
I believe the second item is throwing this error: 我相信第二项抛出此错误:
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)) Mysql2 :: Error:操作数应包含1列:SELECTworkouts
。* FROMworkouts
((user_id = 29)或(user_id = 2,5,29)或(user_id = 2))的ActiveRecord :: StatementInvalid:Mysql2 ::错误:操作数应包含1列:SELECTworkouts
。* FROMworkouts
((user_id = 29)OR(user_id = 2,5,29)OR(user_id = 2))
If that's the case, how can I iterate over the user_id=2,5,29 (other than .each) and pull all the workouts that were created by this specific set of users? 如果是这样,我如何遍历user_id = 2,5,29(.each除外)并提取由该特定用户组创建的所有锻炼?
try this where
query, which will look into array of id's for user_id
match 试试这个where
查询,它将查询user_id
匹配的id数组
Workout.where(user_id: [current_user.id, User.select(&:professional?), User.find_by_admin(true).id].flatten)
Sql equivalent SQL等效
SELECT * FROM workouts WHERE user_id IN (1,3,6,4,2)
尝试这个
Workout.where(user_id: [current_user, User.select(&:professional), User.find_by_admin(true)]).map(&:id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.