Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails export to CSV file

It is partly working. It generates the file but the output is not how I want it.

Controller

@messages = Message.take(2)
  respond_to do |format|
    format.html
    format.csv { send_data @messages.to_csv }
  end

Message.rb

def self.to_csv
    CSV.generate do |csv|
          csv << Message.attribute_names
          Message.all.each do |message|
            csv << message.attributes.values
          end
    end
 end

I get the CSV file downloaded, it contains the records itself but it does not show the columns and values

#<Message:0x007fca7a028338>,#<Message:0x007fca79a6bf58>

I would expect the Message attributes like:

ID,text
1,hello
2,world
like image 868
Lut Avatar asked Feb 12 '26 17:02

Lut


1 Answers

Message.take(2) returns Array. You need ActiveRecord::Relation.

Try Message.limit(2)

like image 141
sbulat Avatar answered Feb 15 '26 10:02

sbulat