0

I'm using postgres database and I have a table like so with array type columns:

 create_table "reports", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
    t.uuid "user_id", null: false
    t.text "assigned_conversation_ids", default: [], array: true
    t.text "first_response_times", default: [], array: true
    t.text "response_times", default: [], array: true
    t.text "close_times", default: [], array: true
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_reports_on_user_id"
  end

I want to append objects (hash) to the first_response_times field.

What I tried:

def update_first_response_time(conversation_id, message_created_at)
  first_response_time = 1000 * (Time.zone.now.to_f - message_created_at.to_f)
  first_response_exists = user_report.first_response_times.select { |first_response_time| JSON.parse(first_response_time).conversation_id == conversation_id }
     
  return if first_response_exists&.size > 0
     
  user_report.first_response_times << `{#{conversation_id}:#{first_response_time}}`
  user_report.save
end

I want to append to the array if the key with conversation_id does not already exist in the array. How do I go about this?

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Mohit Harshan
  • 1,916
  • 1
  • 18
  • 41
  • Why do you use an array, a hash is more suitable solutions for this purpose. – Yakov Sep 26 '22 at 11:05
  • @Yakov I want to save like {conversation_id: 123, response_time: 234} for each of the conversations. There will be multiple number of conversation_ids. Afterwards I will be taking the average of that – Mohit Harshan Sep 26 '22 at 11:08
  • 1
    is jsonb column better to use here? – Mohit Harshan Sep 26 '22 at 11:08
  • The reason, I need to add conversation_id is because if the array already contains the key with the conversation_id, it shouln't be added again. – Mohit Harshan Sep 26 '22 at 11:16
  • 1
    To store `{conversation_id: 123, response_time: 234}` JSOB is the best solution here I suppose. Then you can check if a key exists `user_report.first_response_times.key?(conversation_id)` – Yakov Sep 26 '22 at 11:19
  • @Yakov I'm not checking if key exists. I want store like [ {conversation_id:1, response_time:2}, {conversation_id:2, response_time: 3} ]. if conversation_id with 1 already exists, it should return. – Mohit Harshan Sep 26 '22 at 11:23
  • 1
    You can use `|=` assignment but with a hash it's easier. – Yakov Sep 26 '22 at 11:27

0 Answers0