jeudi 25 juin 2015

How to export models to a CSV file using Rails 3?

I'd like to export all database entries into a csv using Rails 3.2. I've been following these instructions:

My controller:

...
elsif params[:reference] == 'exportnews'
  @data = News.find(:all, :order => "date_posted desc", :conditions => "#{Settings.show} = 1", :limit => "5")
  respond_to do |format|
    format.html { redirect_to root_url }
    format.csv { send_data @data.to_csv }
  end
else
...

My model:

  class News < ActiveRecord::Base
      attr_accessible :content, :date_posted, :heading, :hidden, :reference, :title, :user
      def self.to_csv(options = {})
          CSV.generate(options) do |csv|
            csv << column_names
            all.each do |product|
              csv << product.attributes.values_at(*column_names)
            end
          end
        end
    end

yet when I visit the specified url (I've created a route in config/routes.rb I get a csv file with the following details:

#<News:0x007fef657d69f8> #<News:0x007fef632b95a8> #<News:0x007fef632b8ec8> #<News:0x007fef632b8680> #<News:0x007fef632b7e38>

What am I missing?

Aucun commentaire:

Enregistrer un commentaire