Reputation: 783
I am trying to export data from documents table to spreadsheet using spreadsheet and to_xls gem. I am following this tutorial:
Now a service has_many: documents document belongs_to: service
The service table has a column called name. So instead of displaying service_id on my excel sheet , I want to display service.name
documents/views/index.html.erb
<table id='myDocumentsTable' class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Service</th>
<th>Tat</th>
<th>Automated</th>
<th>Price</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @documents.each do |document| %>
<tr>
<td><%= document.name %></td>
<td><%= document.service.name %></td>
<td><%= document.tat %></td>
<td><%= document.automated %></td>
<td><%= document.default_price %></td>
<td><%= link_to 'Show', document %></td>
<td><%= link_to 'Edit', edit_document_path(document) %></td>
<td><%= link_to 'Destroy', document, method: :delete, data: {
confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= will_paginate @documents %>
<%= link_to 'New Document', new_document_path, class: 'new_doc' %>
<%= link_to 'Export', documents_path(request.parameters.merge({:format
=> :xls})), :class =>"btn btn-primary" %>
documents_controller.rb
def index
@documents = Document.all.paginate(:page => params[:page], :per_page =>
30).order('name ASC')
respond_to do |format|
format.html
format.xls { send_data Document.all.select([:name, :service_id , :tat,
:automated, :default_price]).to_xls, content_type: 'application/vnd.ms-
excel', filename: 'documents.xls' }
end
end
I want to display the exact contents of index.html.erb into an excel sheet where the service column should contain the service.name not the service_id. How can I achieve this? Please help!
Upvotes: 0
Views: 303
Reputation: 23671
You can join the service and use select to get specific attributes from services table
You can use service.name as service_name
which will return you service name
def index
@documents =
Document.all.paginate(page: params[:page], per_page: 30).order('name ASC')
respond_to do |format|
format.html
format.xls do
send_data(
Document.joins(:service)
.select('documents.name, services.name as service_name,
documents.tat, documents.automated,
documents.default_price'
).to_xls,
content_type: 'application/vnd.ms-excel',
filename: 'documents.xls'
)
end
end
end
Upvotes: 1