简体   繁体   中英

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. 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 .* FROM workouts WHERE ((user_id= 29) OR (user_id= 2,5,29) OR (user_id= 2)) ActiveRecord::StatementInvalid: Mysql2::Error: Operand should contain 1 column(s): SELECT workouts .* FROM workouts WHERE ((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?

try this where query, which will look into array of id's for user_id match

Workout.where(user_id: [current_user.id, User.select(&:professional?), User.find_by_admin(true).id].flatten)

Sql equivalent

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM