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
相关产品推荐
相关产品推荐

