Excel filter - Ruby on Rails

0

I have a product form, created with scaffold , I export my records normally to my excel with the current configuration of csv and excel in Ruby on Rails; I want to know if there is a way to export only the products that I want or determined by their name, I have not found anything related on the internet and I have no idea how to do it. Since I have not been involved in this work for a short time, I await your quick response or a page on which you can support me.

Controller:

# app/controllers/products.rb

class ProductsController < ApplicationController
  def index
    @products = Product.order(:name)
    respond_to do |format|
      format.html
      format.csv { send_data @products.to_csv }
      format.xls
    end
  end
end

View:

<!-- app/views/products/index.xls.erb -->

<table border="1">
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Release Date</th>
    <th>Price</th>
  </tr>
  <% @products.each do |product| %>
  <tr>
    <td><%= product.id %></td>
    <td><%= product.name %></td>
    <td><%= product.released_on %></td>
    <td><%= product.price %></td>
  </tr>
  <% end %>
</table>
    
asked by stiven 16.11.2018 в 17:36
source

1 answer

0

The only change you should make filter the collection before exporting it to CSV or XLS , that is, in the driver; in your example it would look something like this:

class ProductsController < ApplicationController
  def index
    @products = Product.where(name: 'Camiseta')

    respond_to do |format|
      format.html
      format.csv { send_data @products.to_csv }
      format.xls { send_data @products.to_csv(col_sep: "\t") }
    end
  end
end

The important line is @products = Product.where(name: 'Camiseta') , in which you are filtering the products to include only those that are called 'Camiseta' .

    
answered by 16.11.2018 / 19:48
source