首页 > 解决方案 > Rails 5 joins where clause on both tables

问题描述

How can I include a where clause on the Reply table with the following query?

Reply.joins(:replier_account).where(replier_accounts: {account_type: 'reply' })

I tried adding it at the end like so:

Reply.joins(:replier_account).where(replier_accounts: {account_type: 'reply' }).where("created_at > ?", 7.days.ago)

But I'm receiving the following error:

ActiveRecord::StatementInvalid: PG::AmbiguousColumn: ERROR:  column reference "created_at" is ambiguous

标签: ruby-on-railsactiverecord

解决方案


该错误告诉您它不知道您希望在哪个表上过滤“created_at”(猜测它们都有“created_at”)。尝试将表名附加到 created_at; 像这样:

Reply.joins(:replier_account)
     .where(replier_accounts: {account_type: 'reply' })
     .where("replier_accounts.created_at > ?", 7.days.ago)

推荐阅读