Ask A Question


You’re not receiving notifications from this thread.

Multiple select for CSV Export

Sascha M. asked in Rails

Hi there,

My users can create a report record which is basically a scaffolded model "Report" with controller and views. The users can use this model to create records that a CSV method is using to query 2 other models: Order (parent) model and the corresponding Sale (child).

The Report model contains these columns:

t.datetime "start" *(for createdat between (?) and (?))*
t.datetime "end" *(for createdat between (?) and (?))*
t.string   "brand" *(brand = ?)*
t.string   "team" *(team = ?)*

Short excerpt of the CSV query looks like that:

Order.where("created_at between (?) and (?) and brand = ? and team = ?", self.start, self.end, self.brand, do |order| order.sales.each do |sale|

This basically outputs each single Sale record in one line. So when 1 Order contains 5 sales, then 5 rows are printed into the CSV file.
That works perfectly with a single brand and a single team.

Now I want to do offer my users multiple select of brands and teams. E.g. when the brand is "Adidas" and "Nike" and the corresponding teams are "US" and "Europe" I want to put both outputs into one CSV instead having the user to create 2 reports.

I'm really struggling with that. What do I need to adjust so that multiple values are getting saved into one record, like brand = "Adidas, Nike" and team = "US, Europe" and then have this array parsed and get that into the CSV AR Query.

Thanks a LOT in advance,


no one? :(


I haven't done this personally but I have some very similar scenarios and I think that if I were doing it, I'd setup a form that has all the options for your user to select which submits their selections to a custom function that will take that input, run my queries, and generate an array or hash to then pass to the csv save function.


Perfect. Thank you for the hint. I've resolved it like this:


<%= :brand, Brand.all.collect {|x| [,]}, {}, :multiple => true, :size => 8 %>


params.require(:report).permit(:title, :start, :end, brand: [])

Model (to remove characters):

    before_save do
    self.brand.gsub!(/[\[\]\"]/, "") if attribute_present?("brand")
    self.brand.gsub!(/\A,|,\Z/, '') if attribute_present?("brand")
    self.brand.gsub!(/, /, ',') if attribute_present?("brand")
    self.brand.strip! if attribute_present?("brand")


        brands = self.brand
        brands = brands.split(',')

to turn it into an array.

then loop through it, with:

brands.each do |b| ...
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,453+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.