ruby-on-rails - ActiveRecord 查询(包含或加入)

标签 ruby-on-rails ruby postgresql rails-activerecord

我有两个类:

class Customer 
    has_many :packages
end

class Package 
    belongs_to :customer
end

如何进行这样的查询?

Customer.includes(:packages).where(packages: 'expires_at < Date.current')

通过控制台的示例测试,我得到了它:Customer Load (26.0ms) SELECT "customers".* FROM "customers" INNER JOIN "packages" ON "packages"."customer_id" = "customers"."id" WHERE (packages.expires_at < '2019-03-13') LIMIT $1 [["LIMIT", 11]] Traceback (most recent call last): ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: operator does not exist: integer = uuid) LINE 1: ...INNER JOIN "packages" ON "packages"."customer_id" = "custome... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. : SELECT "customers".* FROM "customers" INNER JOIN "packages" ON "packages"."customer_id" = "customers"."id" WHERE (packages.expires_at < '2019-03-13') LIMIT $1 irb(main):003:0>

最佳答案

您可以在引号内传递 where 表达式并绑定(bind) expires_at 的值。

Customer.includes(:packages).where('packages.expires_at < ?', Date.current)

关于ruby-on-rails - ActiveRecord 查询(包含或加入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55153644/

相关文章:

ruby-on-rails - Ruby on Rails : Active Record query fails to execute only when hosted on heroku.

postgresql - Postgres 如何从外部服务器传输所有枚举

ruby-on-rails - 在 Grape 和 Grape Entity gem 之间共享描述和类型

html - rails : Image as a link

ruby-on-rails - Ruby 版本 - 安装 Rails 时出错

ruby - 如何使用 ruby​​zip 避免 "Zip end of central directory signature not found (Zip::Error)"?

sql - Ruby on Rails Where 子句小于大于

ruby-on-rails - rails-在连接表中创建记录

mysql - 在 Rails 中获得一个随机的、未投票的帖子

sql - 在两个日期之间取最小值时出错