התייעצות כיצד להשיג מידע משתמשים

סיכום מבוסס בינה מלאכותית

In a Dev. category discussion titled Consultation on how to obtain user information, Programer-D shared a Ruby plugin that searches users via AWS DynamoDB and renders them as cards. The current implementation loops through each user record using User.find(user_data['UserID']), causing a slow 3500ms response for ~1400 users. pfaffman suggested optimizing by fetching all users at once using User.find_by_sql("select * from users where id in (#{user_ids.join(',')})"). Programer-D confirmed this helped, and pfaffman further recommended using user_data.pluck(:UserID) to cleanly extract IDs. Programer-D appreciated the guidance, acknowledging their unfamiliarity with Ruby and expressing intent to refactor using the suggested idiomatic methods. The core issue was inefficient per-record database queries, resolved by batching user lookups and using Ruby’s pluck for cleaner data extraction.

I have created a form as a plugin that searches for a user from a user field that I have defined independently.

I used Web API to store user information in an external DB (AWS DynamoDB) and extract data from it for searching.

class DiscourseUserSearchController < ApplicationController
  def index
  end

  def search
    dynamodb = Aws::DynamoDB::Client.new(
      access_key_id: ENV['ACCESS_KEY_ID'],
      secret_access_key: ENV['SECRET_ACCESS_KEY'],
      region: AWS_REGION
    )

    scan_condition = {
      table_name: "DiscourseUserInformation"
    }
    result = dynamodb.scan(scan_condition)

    result = result.items
    Rails.logger.info result
    data = result.map do |user_data|
      user = User.find(user_data['UserID'])
      user_data['avatar_template'] = user.avatar_template
      user_data['username'] = user.username
      next user_data

    end

    render status: 200, json: { status: 200, data: data }
  end
end

The above code gets all users when the page is opened and passes them to angular.

This works fine, but the response takes 3500 milliseconds, which is not very desirable. (about 1400 search users).

I think the problem is that I am doing User.find(user_data[‘UserID’]) in a loop, but I can’t think of a way to make it better.

I would like to display user cards, so I think it is necessary to acquire users on Ruby, but I would be happy to get suggestions on how to make it faster.

 User.find_by_sql("select * from users where id in (#{user_ids.join(',')})")

Thanks. It looks like it will be resolved.

So that was enough? You might also also do something like

user_ids=user_data.pluck(:UserID)

Thank you!
I wasn’t familiar with Ruby so I accomplished that with dirty code, but I’ll try to improve it the way you’re presenting it!