mysql - 从belongs_to表获取Ruby中的对象集合时出错

标签 mysql ruby-on-rails ruby

在此示例中,我尝试获取由特定类型的用户创建的锻炼集合(锻炼属于特定用户,具有列名称 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.* 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))

如果是这种情况,我如何迭代 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/

相关文章:

php - 在 html 表中使用单选按钮?

Android:将 mysql(XAMPP) 连接到模拟器上的 android 应用程序

mysql - 如何创建使用 mysql/mssql 中的表数据生成插入语句的 sql 脚本

ruby-on-rails - Rails - 如何禁用对本地主机 :3000/users/sign_in on Devise gem? 的访问

ruby - 使用 Watir 时为 "NameError: uninitialized constant UserAgent"

ruby-on-rails - 使用 Sidekiq 进行幂等设计 Ruby on Rails 后台作业

sql - 在 SQL 中为 UNION 使用一个通用的 WHERE 条件

ruby-on-rails - 在 Rails 3.1 中显示来自 acts_as_commentable_with_thread 的 HashWithIndifferentAccess

ruby-on-rails - ruby rails : How do you convert a database entry with attributes inside into a human-readable format?

ruby-on-rails - 你如何在 Rails 中每小时调用一个方法?