I am going create a rail application which takes input from an csv file and show it on the webpage.
After doing all the needful stuffs I am facing this:
Routing Error
uninitialized constant UserController
My app\controllers\users_controller.rb file is:-
class UsersController < ApplicationController
def index
@users=User.all
end
def import
User.import(params[:file])
redirect_to root_url, notice: "Activity data imported!"
end
end
My app\model\user.rb file is:- class User < ActiveRecord::Base require 'csv'
def self.import(file)
CSV.foreach(file.path, headers:true) do |row|
User.create! row.to_hash
end
end
end
My app/views/users/index.html.erb file is:-
<%= flash[:notice] %>
<table>
<thead>
<tr>
<th>Name</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.user %></td>
<td><%= user.age %></td>
</tr>
<% end %>
</tbody>
</table>
<div>
<h4>Import the data!</h4>
<%= form_tag import_users_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import CSV" %>
<% end %>
</div>
My 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: "user#index"
end
I have not posted any #marked commented line from routes.rb file here.
The snapshot of the output screen is here:-
when clicking on the import csv button the following error is shown:
UsersController
toUserController
– caffeinated.techroot to :"users#index"
– Anand