首页 > 解决方案 > 使用 ActiveRecord 或纯 SQL ActiveRecord::AssociationRelation 进行动态搜索的数据库查询

问题描述

在我的数据库中,我没有列company_name,但我有记录,inquiry_fields: { name: 'company_name' }在它们的值下,我将获得带有公司名称的字符串。

要获得一个公司名称,我必须这样做:

first_process = Process.first
                .inquiry_field_responses
                .joins(:inquiry_field)
                .where(inquiry_fields: { name: 'company_name' })

它返回 ActiveRecord::AssociationRelation 所以我必须这样做:

first_process.first&.value

我会得到带有公司名称的字符串

  InquiryFieldResponse Load (0.8ms)  SELECT  "inquiry_field_responses".* FROM "inquiry_field_responses" INNER JOIN "inquiry_fields" ON "inquiry_fields"."id" = "inquiry_field_responses"."inquiry_field_id" WHERE "inquiry_field_responses"."inquiry_process_id" = $1 AND "inquiry_fields"."name" = $2 ORDER BY "inquiry_field_responses"."id" ASC LIMIT $3  [["inquiry_process_id", 55], ["name", "company_name"], ["LIMIT", 1]]
 => "bbbbb"

基于此,如何找到所有带有公司名称的流程,即。“啊”?据我了解,我必须创建查询

Process.joins(process_field_responses, process_field)
       .where(process field name is equal company name and value is equal to aaa) 

所以我在尝试:

Process.joins(inquiry_field_responses: :inquiry_field)
       .where(inquiry_fields: { name: 'company_name' })
       .where("value LIKE ?", "aaa")

但我有一个错误:

ActiveRecord::StatementInvalid(PG::UndefinedColumn:错误:列“值”不存在)

确实,这个专栏不存在。

是否可以创建这样的查询?

[编辑]inquiry_field_responses 列表

  create_table "inquiry_field_responses", force: :cascade do |t|
    t.string "encrypted_value"
    t.bigint "inquiry_process_id"
    t.bigint "inquiry_field_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "custom_flow_model_id"
    t.string "encrypted_value_iv"

标签: sqlruby-on-railsrubyactiverecord

解决方案


推荐阅读