samedi 4 juin 2016

can not export a csv file through a rail application

I am trying to export a csv file through a rail application. I have a previous application which imports the data from a csv file and shows it in the webpage. That application was fired from the url http://localhost:3000/ and it was working fine.

But now I am trying to get back the data shown in the webpage back to a csv file which I can download from the page.

Now I am not sure why I am facing the error. The error is: Routing Error: uninitialized constant UsersController

My code is as follows:-

I created my app name is names My name\app\controllers\names_controller.rb file is:

class NamesController < ApplicationController
require 'csv'
def index
 @names= Name.order(:name)
 respond_to do |format|
    format.html { redirect_to root_url }
    format.csv {send_data @names.to_csv}
    format.xls 
 end
end
end

My name\app\models\names.rb file is:

class Name < ActiveRecord::Base
attr_accessible :age, :name

def self.to_csv(options = {}) 
    CSV.generate(headers: true) do |csv|
        csv << column_names
        all.each do |name|
            csv << name.attributes.values_at(*column_names)
        end
    end
end
end

My name\app\views\names\index.html.erb file is:

<h1>Names</h1>

<p>
Download:
<%= link_to "CSV", names_path(format: "csv") %> |
<%= link_to "Excel", names_path(format: "xls") %>
</p>

My name\app\views\names\index.xls.erb file is:

<table border="1">
<tr>
<th>Age</th>
<th>Name</th>
</tr>
<% @names.each do |name| %>
<tr>

<td><%= product.age %></td>
<td><%= product.name %></td>


</tr>
<% end %>

</table>

My names\config\routes.rb file is:

Rails.application.routes.draw do

get 'users/index'

get 'users/import'

resources :users do
collection {post :import}
end
root to: "users#index"

end

My previous application database screenshot is:- The columns names are Age and Name respectively

Aucun commentaire:

Enregistrer un commentaire