I'm working to export CSV data from Rails. I'm following the tutorial here: http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast
In my controller I have:
def show
# @company is being provided correctly.
@groups = @company.groups
render text: @groups.to_csv
end
In my group.rb model:
def self.to_csv
Rails.logger.info "Hello World"
CSV.generate do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
The issue is the browser is outputting just the following:
#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#
The model method appears to be being ignored, even after a Rails restart. What's wrong here?
The to_csv is a class method. Meaning its meant to be called like Group.to_csv. You might want to change the method signature to something like Group.to_csv(groups) instead.
def self.to_csv(groups)
Rails.logger.info "Hello World"
CSV.generate do |csv|
csv << column_names
groups.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
Then in show
def show
# @company is being provided correctly.
@groups = @company.groups
render text: Group.to_csv(@groups)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With