如何在Rails 5中查询“有很多通过”关系

时间:2018-10-17 06:50:16

标签: ruby-on-rails activerecord

我有一个具有以下型号的Rails 5应用程序:

User.rbCampaign.rbUserCampaign.rb

该关系为User has many Campaigns through UserCampaign。通过这种关系,我可以查询@user.campaigns来查找与该用户相关的所有广告系列。到目前为止一切顺利。

UserCampaign模式如下:

create_table "user_campaigns", force: :cascade do |t|
  t.bigint "campaign_id"
  t.bigint "user_id"
  t.boolean "responded", default: false
  t.index ["campaign_id"], name: "index_user_campaigns_on_campaign_id"
  t.index ["user_id", "campaign_id"], name: "index_user_campaigns_on_user_id_and_campaign_id"
  t.index ["user_id"], name: "index_user_campaigns_on_user_id"
end

理想情况下,我想写@user.campaigns.where(responded: false)。但是,出现以下错误:

PG::UndefinedColumn: ERROR: column campaigns.responded does not exist LINE 1: ...izard_id" WHERE "user_campaigns"."user_id" = $1 AND "campaigns".... ^ : SELECT "campaigns".* FROM "campaigns" INNER JOIN "user_campaigns" ON "campaigns"."id" = "user_campaigns"."campaign_id" WHERE "user_campaigns"."user_id" = $1 AND "campaigns"."responded" = $2

我知道我得到这个是因为responded是UserCampaign上的一列,而不是Campaign上的一列。进行联接以包括响应列的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

  

PG :: UndefinedColumn:错误:列Campaigns.responded不存在

您应该像下面那样重写查询

@user.campaigns.joins(:user_campaigns).where(user_campaigns: {responded: false})