I'm not quite sure what I am overlooking when attempting to allow csv download on my Game model and I'm getting a little lost.
On the profile show page I render an index like list of games associated with that user, i.e. their game schedule.
The Profiles Controller-
def show
#user = User.find_by_profile_name(params[:id])
if #user
#listings = #user.listings
#games = #user.games
respond_to do |format|
format.html
format.csv {send_data #games.to_csv}
end
return
render action: :show
else
render file: "public/404", status: 404, formats: [:html]
end
end
Then in the game.rb I define the method to_csv
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |item|
csv << item.attributes.values_at(*column_name)
end
end
end
And on the profile show page to download the expected csv game schedule
<%= link_to "Download my Schedule", profile_path(format: 'csv')%>
I believe this might be my issue lies, but that doesn't quite explain what I get in my csv which is just a game object
file-
Here is my routes.rb
resources :games
match 'friendships/:friend_id' => 'user_friendships#new', :as => :new_friendship
match 'dashboard' => 'dashboard#show', :as => :dashboard
root to: "profiles#index"
get '/players', to: 'profiles#index', as:'players'
get '/players', to: 'profiles#index', as:'users'
get '/:id', to: "profiles#show", as: 'profile'
The file should be formatted with the column names (location, opponent, time, etc) as the header line and the corresponding lines with their respective values for each instance associated to a user.
I think the to_csv method inside game should be re-declared as -
passed in the games array which needed to be converted.
the param passed to values_at is column_names not column_name.
def self.to_csv(games)
CSV.generate do |csv|
csv << column_names
games.each do |item|
csv << item.attributes.values_at(*column_names)
end
end
end
and in the controller, the code should be:
def show
#user = User.find_by_profile_name(params[:id])
if #user
#listings = #user.listings
#games = #user.games
respond_to do |format|
format.html
format.csv {send_data Game.to_csv(#games)}
end
return
render action: :show
else
render file: "public/404", status: 404, formats: [:html]
end
end
otherwise, you will output all the games no matter which user you are using.
Although cenjongh's answer isn't wrong, let me elaborate on it.
The syntax Game.to_csv(#games) goes against Ruby's/Rails' object oriented approach for me.
Since the CSV generation code in your case is totally model independent (you don't make any assumptions of column names, etc.) you could feed this method any array of models, i.e. Game.to_csv(#shampoos) which would still work but wouldn't read very well.
Since Rails scopes the all method according to the criteria attached to the ActiveRelation object, using it in your class method wouldn't result in an output of all the games.
Assuming you're using at least Rails 3.0 the line #games = #user.games would give you an ActiveRelation object, not an array, meaning you can call #games.to_csv (or to make it even clearer #user.games.to_csv) directly, which reads what it is, namely converting a list of games, that belong to a user into CSV.
Oh, and I guess this is just testing code, but the return shouldn't be there. And the render statement should go into the block of format.html.
Related
I'm making an export to csv file functionality in a Ruby on Rails repo and I'm almost done. However, when I press the "Export all" button, I get the undefined method `export' for nil:NilClass error. The log shows that format.csv { send_data #foos.export, filename: "foos-#{Date.today}.csv" } went wrong. What am I missing please?
This is model
class Foo < ApplicationRecord
has_many :bars
def export
[id, name, foos.map(&:name).join(' ')]
end
end
This is part of controller
def index
#foos = Foo.all
end
def export
all = Foo.all
attributes = %w{name}
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |foo|
csv << attributes.map{ |attr| foo.send(attr) }
end
respond_to do |format|
format.csv { send_data #foos.export, filename: "foos-#{Date.today}.csv" }
end
end
end
def name
"#{foo_id} #{name}"
end
This is View
<button class="btn btn-success">export all</button>
This is Routes
Rails.application.routes.draw do
resources :foos
get :export, controller: :foos
root "foos#index"
end
This is Rake (lib/tasks/export.rb)
namespace :export do
task foo: :environment do
file_name = 'exported_foo.csv'
csv_data = Foo.to_csv
File.write(file_name, csv_data)
end
end
Start by creating a service object that takes a collection of records and returns CSV so that you can test the CSV generation in isolation:
# app/services/foo_export_service.rb
# Just a Plain Old Ruby Object that converts a collection of foos into CSV
class FooExportService
# The initializer gives us a good place to setup our service
# #param [Enumerable] foo - an array or collection of records
def initialize(foos)
#headers = %w{name} # the attributes you want to use
#foos = foos
end
# performs the actual work
# #return [String]
def perform
CSV.generate do |csv|
#foos.each do |foo|
csv << foo.serializable_hash.slice(#headers).values
end
end
end
# A convenient factory method which makes stubbing the
# service easier
# #param [Enumerable] foos - an array or collection of records
# #return [String]
def self.perform(foos)
new(foos).perform
end
end
# example usage
FooExportService.perform(Foo.all)
Not everything in a Rails application needs to be jammed into a model, view or controller. They already have enough responsiblities. This also lets you resuse the code for example in your rake task if you actually need it.
This simply iterates over the collection and uses Rails built in serialization features to turn the model instances into hashes that can be serialized as CSV. It also uses the fact that Hash#slice also reorders the hash keys.
In your controller you then just use the service object:
class FoosController
def export
#foos = Foo.all
respond_to do |format|
format.csv do
send_data FooExportService.perform(#foos),
filename: "foos-#{Date.today}.csv"
end
end
end
end
You don't even really need a separate export action in the first place. Just use MimeResponds to add CSV as an availble response format to the index:
class FoosController
def index
# GET /foos
# GET /foos.csv
#foos = Foo.all
respond_to do |format|
format.html
format.csv do
send_data FooExportService.perform(#foos),
filename: "foos-#{Date.today}.csv"
end
end
end
end
<%= link_to("Export as CSV", foos_path(format: :csv)) %>
AcitveAdmin provides a link at the bottom of the index page to download all resources in multiple formats, and one of the formats is CSV. It is gonna take all the resources, put them in a CSV file, and give that back to us. In my situation, I have a condition that there are certain resources that can be downloaded via CSV, like:
User.downloadables
But I'm unable to figure it out how to give this set instead of User.all to CSV format?
I have looked into documentation, and it doesn't say much except changing the layout of a CSV file.
Apparently, I couldn't find a way to pass a specific set of records to CSV file, so I wrote the custom controller method for it in ActiveAdmin, and that's how I accomplished it:
app/models/user.rb:
scope :downloadables, -> { where(status: :downloadable) }
def self.to_csv
downloadable_users = User.downloadables
CSV.generate do |csv|
csv << column_names
downloadable_users.each do |user|
csv << user.attributes.values_at(*column_names)
end
end
end
app/admin/user.rb:
First, I generated a collection action that will let us download CSV file:
collection_action :download_csv do
redirect_to action: :download_csv
end
Now, to have a link on index page through which one would be able to download the records in CSV file:
action_item only: :index do
link_to "Download CSV", download_csv_admin_users_path
end
And finally to have a controller method that will actually call the method from model, and do the rest of the magic:
controller do
def download_csv
respond_to do |format|
format.html { send_data User.to_csv, filename: "users-#{Data.today}.csv" }
end
end
end
And that's it. It is working.
You can also customize the csv export as well for active admin.
ActiveAdmin.register Post do
csv force_quotes: true, col_sep: ';', column_names: false do
column :title
column(:author) { |post| post.author.full_name }
end
end
Cheers
I am trying to export some data to CSV in Rails 4. I have two models: Excursions and Inscriptions. One excursion has many inscriptions and one inscription belongs to one excursion.
I have my nested routes defined this way:
resources :excursions do
resources :inscriptions
get 'exportcsv' => 'excursions#download'
end
So the behavior I am trying to achieve is: when I visit the route /excursions/1/exportcsv, a CSV will be downloaded to my computer and it will contain all the inscriptions with excursion_id = 1 in CSV format.
In my excursion model I have defined self.to_csv:
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
self.inscriptions.each do |inscription|
csv << inscription.attributes.values_at(*column_names)
end
end
end
And my excursion controller's method download:
def download
#excursion = Excursion.find(params[:id])
respond_to do |format|
format.html
format.csv { send_data #excursion.to_csv }
end
end
EDIT: When I go to a route like: /excursions/:id/exportcsv the server is throwing an ActiveRecord::RecordNotFound error. This error is easy to solve, but if I solve the RecordNotFound I get an ActionController::UnknownFormat in this line:
def download
#excursion = Excursion.find(params[:id])
respond_to do |format| ########THIS LINE
format.html
format.csv { send_data #excursion.to_csv }
end
end
What I am doing wrong? Maybe all this approach is not correct...
I would update the routes to the following:
resources :excursions do
get 'download', on: :member, constraints: { format: /(html|csv)/ }
resources :inscriptions
end
Also there is a bug in your model code. You are exporting inscriptions but are using Excursion column_names instead of Inscription column_names. Following is the updated model code.
class Excursion < ActiveRecord::Base
def to_csv(options = {})
CSV.generate(options) do |csv|
inscription_column_names = Inscription.column_names
csv << inscription_column_names
self.inscriptions.each do |inscription|
csv << inscription.attributes.values_at(*inscription_column_names)
end
end
end
Now try to access http://localhost:3000/excursions/:id/download.csv
Replace :id with an existing Excursion records id. If you still encounter ActiveRecord::RecordNotFound error, then the problem could be that you are trying to access an Excursion that doesn't actually exist in the database.
This is more of an architecture/functional question for Rails. I have a search function which sends the criteria to the model where the query resides. The search works. Now I have a CSV export link <%= link_to "CSV", contacts_path(format: "csv") %> in my view file which points to localhost/books.csv.
The export didn't work without my search parameters (so localhost/book.csv?book_name=foo works as expected). What I do in send_data is I pass the #books object to the .to_csv function inside my model, and it becomes nil without passing the parameter also. Pls see code below.
My controller:
def index
#books = Book.search(params[:search])
respond_to do |format|
format.html
format.csv { send_data Book.to_csv(#books) }
end
My model:
def self.search(criteria)
find(:all, :conditions => ['book_name LIKE ?', "%#{criteria}%"])
end
def self.to_csv(search_results)
CSV.generate do |csv|
csv << column_names
search_results.each do |contact|
csv << contact.attributes.values_at(*column_names)
end
end
end
I like to understand why. The current setup seems to be making another request to the server in order to generate the CSV file, and that's why it requires the parameters in localhost/books.csv request. Is this correct?
Now, if instead I put the query inside the controller like below, the CSV request works as expected (so I just click the link and receive the file).
def index
#books = Book.find(:all, :conditions => ['book_name LIKE ?', "%#{criteria}%"]) respond_to do |format|
format.html
format.csv { send_data Book.to_csv(#books) }
end
I love to keep the query inside the model for the sake of organization, so would be awesome if you guys can point me to the right direction. Thanks!
I would suggest that you change your link to something like this:
<%= link_to "CSV", contacts_path(params.merge(format: "csv")) %>
This will pass down the current search parameters plus the new option for the format to be CSV. Then you can continue to keep the search method inside the model in the way that you had originally written it.
so i've got a view method in multiple controllers which mostly looks exactly the same:
def show
show! do |format|
format.json do
if #text.activated?
#text.log
render_for_api :texts_all, :json => #text
else
render :nothing => true
end
end
format.pdf do
pdf = QrPdf.new(#text)
send_data pdf.render, filename: "text_#{#text.id}.pdf", type: "application/pdf"
end
end
end
the models for this are different, but they all have the same attributes that are used in this method (activated, log, id). i also could change the render_for_api given hash from which is currently texts_all, documents_all etc to a hash that its everywhere the same.
is there a way to use this code in multiple models without having this enormous duplication?
i'm thankful for every hint!
especially i find it hard to deal with the do |format| block. but also i'm not sure where to put the code and how to use it with different types of models.
thank you.
If the model is truly generic:
def show
show_model #text
end
I'm not sure what show! is, but that part you can figure out. Roughly (untested):
def show_model(obj)
show! do |f|
f.json do
return render(:nothing => true) unless obj.activated?
obj.log
render_for_api :texts_all, :json => obj
end
f.pdf do
opts = { filename: "text_#{obj.id}.pdf", type: "application/pdf" }
send_data QrPdf.new(obj).render, opts
end
end
end
As far as where show_model lives, I tend to put things like that into a base controller, or as a mixin, but there may be better options. Since I usually have a base controller, it's just easy to keep it there.