Database query for dynamic search with ActiveRecord or pure SQL ActiveRecord::AssociationRelation

六月ゝ 毕业季﹏ 提交于 2020-01-06 04:52:15

问题


In my db I don't have column company_name but I have records that inquiry_fields: { name: 'company_name' } and under their value I will get string with company name.

To get one company name I have to do:

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

which returns ActiveRecord::AssociationRelation so I have to do:

first_process.first&.value

And I will get string with company name

  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"

Based on that how to find all Processes with company name ie. 'aaa' ? From what I understand, I have to create query like

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

So I was trying with:

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

but I've got an errror:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column "value" does not exist)

and it's true, this column doesn't exist.

Is it possible to create such a query?

[EDIT] inquiry_field_responses columns table

  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"

来源:https://stackoverflow.com/questions/58557539/database-query-for-dynamic-search-with-activerecord-or-pure-sql-activerecordas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!