'Rails' export csv function "undefined method `export' for nil:NilClass"

I'm making an export to csv file functionality in a Ruby on Rails repo and I'm almost done. However, when I press the "Export all" button, I get the undefined method `export' for nil:NilClass error. The log shows that format.csv { send_data @foos.export, filename: "foos-#{Date.today}.csv" } went wrong. What am I missing please?

This is model

class Foo < ApplicationRecord
  has_many :bars 

  def export
    [id, name, foos.map(&:name).join(' ')]
  end
end

This is part of controller

  def index
    @foos = Foo.all
  end

  def export
    all = Foo.all
    attributes = %w{name}
    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |foo|
        csv << attributes.map{ |attr| foo.send(attr) }
      end

      respond_to do |format|
          format.csv { send_data @foos.export, filename: "foos-#{Date.today}.csv" }
      end
    end
  end

  def name
    "#{foo_id} #{name}"
  end

This is View

<a href="/export.csv"><button class="btn btn-success">export all</button></a>

This is Routes

Rails.application.routes.draw do
  resources :foos
  
  get :export, controller: :foos

  root "foos#index"
end

This is Rake (lib/tasks/export.rb)

namespace :export do
    task foo: :environment do
      file_name = 'exported_foo.csv'
      csv_data = Foo.to_csv
   
      File.write(file_name, csv_data)
    end
  end


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source