You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5.2中如何按ID和属性查询多态关联的项目?

Rails 5.2 按特定自定义字段答案查询项目的实现方法

可以通过以下几种方式实现查询需求:

方法一:关联查询+条件过滤

通过joins关联customfield_answers表,配合where添加过滤条件,最后用distinct避免重复结果:

Project.joins(:customfield_answers)
       .where(customfield_answers: {
         customfield_id: 你的自定义字段ID,
         answer: "目标答案字符串",
         answerable_type: "Project"
       })
       .distinct

方法二:子查询方式

利用where配合子查询,直接筛选出关联符合条件的CustomfieldAnswer的Project:

Project.where(id: CustomfieldAnswer.where(
  answerable_type: "Project",
  customfield_id: 你的自定义字段ID,
  answer: "目标答案字符串"
).select(:answerable_id))

补充:确保关联定义正确

要保证Project模型中已正确声明多态关联:

class Project < ApplicationRecord
  has_many :customfield_answers, as: :answerable
end

如果需要复用查询逻辑,可以封装成类方法:

class Project < ApplicationRecord
  has_many :customfield_answers, as: :answerable

  def self.with_customfield_answer(customfield_id, answer_value)
    joins(:customfield_answers)
      .where(customfield_answers: {
        customfield_id: customfield_id,
        answer: answer_value,
        answerable_type: "Project"
      })
      .distinct
  end
end

调用时直接使用Project.with_customfield_answer(1, "需要匹配的答案")即可。

内容的提问来源于stack exchange,提问作者Mark Denn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:20:51