Rails 5在两个表上联接where子句

时间:2018-10-17 13:23:23

标签: ruby-on-rails activerecord

如何通过以下查询在Reply表上包含where子句?

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

我尝试像这样在最后添加它:

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

但是我收到以下错误:

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

重写此查询的另一种方法是将WHERE条件合并到一个调用中。

要获取最近7天内创建帐户的回复,请执行以下操作:

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

或者,要提取最近7天创建的回复:

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