You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails Active Admin:如何在仪表盘页面添加CSV上传功能

How to Add a CSV Upload Form to Active Admin Dashboard That Triggers a Sidekiq Worker

Got it, let's walk through this step by step. Since the Active Admin Dashboard doesn't come with a dedicated controller by default, we'll add a custom route and action directly within the Dashboard page definition—no extra resource files needed.

Step 1: Add a Custom Route for the Upload Action

First, we need a POST route that our form can submit to. Open up config/routes.rb and add this line right after ActiveAdmin.routes(self):

# Route for Dashboard CSV upload action
post '/admin/dashboard/import_listings', to: 'admin/dashboard#import_listings', as: :admin_dashboard_import_listings

This creates a named route pointing to a custom import_listings action we'll define next.

Step 2: Define the Upload Action and Add the Form to the Dashboard

Update your Dashboard code to include the controller action (to handle the upload) and the form itself. Here's the full updated code:

ActiveAdmin.register_page "Dashboard" do
  menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") }

  # Define the custom controller action inside the Dashboard
  controller do
    def import_listings
      if params[:file].present?
        # Important: Copy the uploaded file to a persistent temp location
        # Rails deletes the default upload temp file after the request ends, which would break the Sidekiq worker
        temp_file = Tempfile.new(["dealer_csv", ".csv"], Rails.root.join("tmp"))
        temp_file.binmode
        temp_file.write(params[:file].read)
        temp_file.close

        # Enqueue the Sidekiq worker with the temp file path
        CsvWorker.perform_async(temp_file.path)

        # Let the user know the import started
        flash[:notice] = "CSV import has been started! It will process in the background."
      else
        flash[:alert] = "Please select a CSV file to upload."
      end

      # Redirect back to the Dashboard
      redirect_to admin_dashboard_path
    end
  end

  content title: proc{ I18n.t("active_admin.dashboard") } do
    div class: "blank_slate_container", id: "dashboard_default_message" do
      span class: "blank_slate" do
        span "Welcome To Want A Car Buy A Car Backend!"
        small "Use options below for CSV uploads:"
      end
    end

    # Add columns and the upload form
    columns do
      column do
        panel "CSV Uploads for Dealers" do
          # Use our named route for the form action
          form_tag admin_dashboard_import_listings_path, multipart: true do
            file_field_tag :file, accept: ".csv" # Restrict to CSV files only
            submit_tag "Import CSV", class: "button"
          end
        end
      end

      # Add more columns here for other upload types if needed
      # column do
      #   panel "Another CSV Upload" do
      #     # Similar form pointing to another custom action
      #   end
      # end
    end
  end # content
end

Step 3: Update the Sidekiq Worker to Clean Up Temp Files

Since we're using a persistent temp file, we should delete it after the worker finishes processing to avoid cluttering the tmp directory. Update your CsvWorker:

class CsvWorker
  include Sidekiq::Worker
  sidekiq_options retry: false

  def perform(file_path)
    begin
      # Run your import logic
      imported = Listing.import_listings(file_path)
      # Optional: Log results or send notifications here
    ensure
      # Always delete the temp file, even if the import fails
      File.delete(file_path) if File.exist?(file_path)
    end
  end
end

Key Details to Note:

  • Custom Route & Action: We added a dedicated route and action directly within the Dashboard's controller block, so we don't need a separate Admin resource.
  • Temp File Handling: Copying the upload to our own temp file ensures the Sidekiq worker can access it (since Rails' default temp files get deleted after the request completes).
  • User Feedback: Flash messages let users know if their upload was accepted or if they missed selecting a file.
  • File Restriction: The accept: ".csv" attribute limits uploads to CSV files, reducing unnecessary errors.

内容的提问来源于stack exchange,提问作者Saurav Prakash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:28:28