Sean Lao Sean Lao - 5 months ago 14
Ruby Question

Rails export array of hash to csv

in my

show
route, there is a
my_search
route (basically
show#my_search
) that shows an array of hashes of data in HTML.

What I need to do is just dump
@data
into my
render
(or partial) and deal with them in views, making it a HTML table with embedded ruby.

However, is there a easy way to send the same
@data
to a CSV file? Do I have to get the
@data
again and make another route specially for it? Is it a way to access the
@data
(preferably, in a link to download its CSV or json render) when showing the page
localhost://show/my_search
?

Edit:

The
@data
looks like:

@data = [ {"name"=>"John", "age"=>"21"}, {"name"=>"Amy", "age"=>"20"} ]


The
app/controllers/show_controller.rb
looks like:

def my_search
@data = [ {"name"=>"John", "age"=>"21"}, {"name"=>"Amy", "age"=>"20"} ] # and other rows
# and do other stuff here

render "table_template"


in
app/views/show/table_template.html
looks like:

<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>

<tbody>
<% @data.each do |row| %>
<tr>
<td><%= row['name'] %></td>
<td><%= row['age'] %></td>
</tr>
<% end %>
</tbody>
</table>





Update 6/20/2016: my current workround:

app/controllers/show_controller.rb
:

def my_search
get_data
# and do other stuff here

render "table_template"
end

def my_search_export
get_data
format.each do |format|
# something that renders the CSV format when visiting localhost://my_search_export.csv
.....
end
end




private
def get_data # writes to @data
@data=[ {"name"=>"John", "age"=>"21"}, {"name"=>"Amy", "age"=>"20"} ]
end


in view: add a url to
localhost://my_search_export.csv
.

Bad thing is it loads the data again, good thing is the workflow is simple. I am still looking for a better solution.

P.s. this website may have different user running at the same time so keeping a global variable doesn't sound right for me.

Answer

Update 6/20/2016: my current workround:

app/controllers/show_controller.rb:

def my_search get_data # and do other stuff here

render "table_template"

end

def my_search_export get_data format.each do |format| # something that renders the CSV format when visiting localhost://my_search_export.csv ..... end end

private def get_data # writes to @data @data=[ {"name"=>"John", "age"=>"21"}, {"name"=>"Amy", "age"=>"20"} ] end in view: add a url to localhost://my_search_export.csv.

Bad thing is it loads the data again, good thing is the workflow is simple. I am still looking for a better solution.

P.s. this website may have different user running at the same time so keeping a global variable doesn't sound right for me.