将参数中的自定义值输入到 Rails SQL 查询



我已经编写了这样的代码来查询在特定时间和特定位置慢跑的用户列表,但我收到以下错误:ActiveRecord::StatementInvalid: SQLite3::SQLException: near "'jogging'"

这是否意味着我无法将字符串写入该变量? 对此有什么解决方案吗?

users = User.where('ids in (:user_ids)', user_ids: 
             Activity.where('title :title AND created_at >= :created_at AND location_id: location_id', 
             {title: 'jogging', created_at: Time.zone.now.beginning_of_day, location_id: 
             Location.where('id in id', id: user.activities.where.not(location_id: nil)
            .order('created_at DESC').first)}))

您可以通过这种方式简化查询

location_id = Location.where(
                             id: user.activities
                                     .where.not(location_id: nil)
                                     .order('created_at DESC').first
                            )
user_ids    = Activity.where("title = ? AND created_at > ? AND location_id = ?", 
                             "jogging", Time.zone.now.beginning_of_day, location_id)
users       = User.where(id: user_ids)

但是如果你想保持查询一行。你可以使用这个

User.where('id IN(:user_ids)', 
            user_ids:  Activity.where('title = :title AND created_at >= :created_at AND location_id = :location_id', title: 'jogging', created_at: Time.zone.now.beginning_of_day, 
            location_id: Location.where('id IN(:id)', id: user.activities.where.not(location_id: nil)
            .order('created_at DESC').first).ids)
          )

注意:我假设您在一个行查询上方使用用户对象

希望这对您有所帮助。

我想你忘了在查询中添加=

您的查询:

Activity.where('title :title ...

你想要什么:

Activity.where('title = :title ...

如果您不需要像 >< 这样的运算符,您还可以使用:

Activity.where(title: title)

如果你需要链接它,这很简单:

Activity.where(title: title).where('foo < ?', 100)

最新更新