I'm having trouble exporting my filtered results to a csv.
I tried following some info I found in issue #25 that had similar trouble.
I'm using rails 7 and the filterrific 5.2.3
Controller index action:
def index
@filterrific = initialize_filterrific(
Result,
params[:filterrific],
select_options: {
sorted_by: Result.options_for_sorted_by,
},
default_filter_params: {},
) or return
@results = @filterrific.find.page(params[:page])
respond_to do |format|
format.html
filename = "Result-#{Time.now.to_date.to_s}.csv"
format.csv { send_data @results.to_csv(), filename: "filename"}
end
end
Model:
class Result < ApplicationRecord
belongs_to :customer
belongs_to :user
require 'csv'
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' },
available_filters: [
:sorted_by,
:with_survey_only,
:with_offer_only,
]
)
scope :sorted_by, ->(sort_option) {
direction = /desc$/.match?(sort_option) ? "desc" : "asc"
case sort_option.to_s
when /^created_at_/
order("results.created_at #{direction}")
else
raise(ArgumentError, "Invalid sort option: #{sort_option.inspect}")
end
}
scope :with_survey_only, lambda { |flag|
return nil if 0 == flag
where(survey: true)
}
scope :with_offer_only, lambda { |flag|
return nil if 0 == flag
where(offer: true)
}
def self.options_for_sorted_by
[
["Created date (newest first)", "created_at_desc"],
["Created date (oldest first)", "created_at_asc"],
]
end
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |result|
csv << result.attributes.values_at(*column_names)
end
end
end
end
and in my view:
<%= link_to "Export as CSV", results_path(format: :csv, filterrific: @filterrific.to_hash) %>
I'm getting this problem with it:
no implicit conversion of Hash into String
def self.to_csv(options = {})
CSV.generate(options) do |csv| <----problem at this line
csv << column_names
all.each do |result|
csv << result.attributes.values_at(*column_names)
I'm still learning, so have probably got something obvious wrong.
I'm having trouble exporting my filtered results to a csv.
I tried following some info I found in issue #25 that had similar trouble.
I'm using rails 7 and the filterrific 5.2.3
Controller index action:
Model:
and in my view:
<%= link_to "Export as CSV", results_path(format: :csv, filterrific: @filterrific.to_hash) %>
I'm getting this problem with it:
no implicit conversion of Hash into String
I'm still learning, so have probably got something obvious wrong.