Moosa
Moosa

Reputation: 3216

Rails 4 download to CSV

I'm building a marketplace app so sellers can list items to sell. I'm trying to download a CSV by seller so sellers can download their own listings.

I'm following the code in this railscast. I got the railscasts code to work as-is. It downloads all the data from my model into a csv. But when I add a seller filter to the query, it doesn't apply the filter.

In listings_controller:

def index
  @listings = Listing.not_expired.order("created_at DESC")  
    respond_to do |format|
      format.html
      format.csv { send_data @listings.to_csv }   
    end
end

def seller
  @listings = Listing.where(user: current_user).order("created_at DESC")
  respond_to do |format|
    format.html
    format.csv { send_data @listings.seller_csv }  
  end
end

in listing.rb:

def self.to_csv
  CSV.generate do |csv|
    csv << column_names
    all.each do |listing|
      csv << listing.attributes.values_at(*column_names)
    end
  end
end

def self.seller_csv
  CSV.generate do |csv|
    csv << column_names
    where(user: current_user).each do |listing|
      csv << listing.attributes.values_at(*column_names)
    end
  end
end

The to_csv methods works fine and downloads all listings. But the seller_csv method also downloads all listings. I need it to filter by current_user. What am I missing?

Upvotes: 0

Views: 240

Answers (1)

Make your function take a list of listings as parameter.

def self.to_csv(listings)
  CSV.generate do |csv|
    csv << column_names
    listings.each do |listing|
      csv << listing.attributes.values_at(*column_names)
    end
  end
end

Then you cane re-use the same function in the two scenarios

def index
  @listings = Listing.not_expired.order("created_at DESC")  
    respond_to do |format|
      format.html
      format.csv { send_data Listing.to_csv(@listings) }   
    end
end

def seller
  @listings = Listing.where(user: current_user).order("created_at DESC")
  respond_to do |format|
    format.html
    format.csv { send_data Listing.to_csv(@listings) }  
  end
end

Your code didn't make really sense as you were fetching listings in your controller but never re-used those fetched objects and was re-calling DB in your model's static functions.

Upvotes: 2

Related Questions