如何在 Rails 5 中查询'Has many Through'关系



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

User.rbCampaign.rbUserCampaign.rb

关系是User has many Campaigns through UserCampaign.有了这种关系,我可以查询@user.campaigns以查找与该用户相关的所有广告系列。目前为止,一切都好。

用户活动架构如下所示:

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是用户广告系列而不是广告系列的专栏。进行联接以包含响应列的最佳方法是什么?

PG::UndefinedColumn: ERROR: column campaign.response 不存在

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

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

相关内容

  • 没有找到相关文章

最新更新