undefined method `[]' for nil:NilClass while importing csv file in rails - csv

I have an application on which I want to provide the feature to import the records from CSV and Excel file formats. I am using roo gem for it, but at the time of importing it gives the error "undefined method `[]' for nil:NilClass".
Here is the code :
student.rb :
require 'roo'
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path, nil, :ignore)
when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
student_controller.rb :
def import
Student.import(params[:file])
redirect_to students_path, notice: "Record imported Successfully."
end
new.html.erb :
<%= form_tag import_students_path, multipart: true do %>
<%= file_field_tag :file , :required=> true%> <br/>
<%= submit_tag "Import" , :class => "btn btn-primary btn-block" %>
<% end %>
Tell me what i am doing wrong?

Related

Validation problems while creating record through file import using Roo gem and following railscast

I am trying to create records through file imports format can be csv excel etc
and I have implemented it following the Railscast396. but as I import file it says
"Validation failed: Email can't be blank, Password can't be blank. Here is my code
class Student < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :quizzes
has_many :classrooms
#to import file
**def self.attr_names
[:email, :password, :password_confirmation]
end**
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
row.inspect
student = find_by_id(row["id"]) || new
student.attributes = row.to_hash.slice(*attr_names)
student.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path, file_warning: :ignore)
when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
view is
<%= form_tag addStudents_classrooms_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
routes.rb
resources :classrooms do
collection { post :addStudents }
csv file i am trying to load
id,email,password,password_confirmation
22,jim#gmail.com,password,password
23,jimhanks#gmail.com,password,password
This is probably happening because #to_hash doesn't return a hash with indifferent access. You're trying to slice symbolized keys and #to_hash created keys as strings.
Try this:
def self.attr_names
%w(email password password_confirmation)
end

How to do resolve this? Exporting CSV in Rails 4

I need export archive CSV in my project. Can anyone help me?
My controller
def export
#travel = Travel.find(params[:id])
#expense = #travel.expenses
respond_to do |format|
format.html
format.csv
end
end
My routes
resources :travels do
get 'export' , to: 'travels#export', as: :export
end
Rake routes
travel_export GET /travel/:travel_id/export(.:format) travels#export
My link to download
<%= link_to "CSV", travel_export_path(#travel,format: "csv") %>
My travel.rb
class Travel < ActiveRecord::Base
belongs_to :user
has_many :expenses
end
And finally, my export.csv.rb! I don't know what I need do here.
<%
headers = [
"User",
"Date",
"Location",
"Total",
"Expense",
"Expense value"
]
csv_output = CSV.generate do |csv|
csv << headers
csv << [
current_user,
date.strftime("%d-%m-%Y"),
location,
total
]
#travel_expenses.each do |expense|
csv<<[
expense.typ.description,
expense.value,
]
end
%>
<%= csv_output.html_safe %>
Please, I need help!
I think you are missing one end in export.csv.rb file at the end of #travel_expenses.each

Referencing the session controller from the user controller to check if a user is logged in

NoMethodError in UsersController#show
undefined method `signed_in?' for #<UsersController:0x5bf3980>
Rails.root: C:/test_app
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:91:in `signed_in_user'
Request
Parameters:
{"id"=>"1"}
Show session dump
Show env dump
Response
Headers:
None
In Users_Controller
def signed_in_user
redirect_to signin_path, notice: "Please Sign In." unless signed_in?
end
In SessionsController
def signed_in?
!current_user.nil?
end
module SessionsHelper
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user = user
end
def sign_out
cookies.delete(:remember_token)
self.current_user = nil
end
def current_user=(user)
#current_user = user
end
def current_user
#current_user ||= user_from_remember_token
end
def signed_in?
!current_user.nil?
end
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
#title = "Sign In"
render 'new'
else
sign_in user
flash.now[:error] = "Welcome, #{user.name}"
render 'AdCon'
end
end
def destroy
sign_out
redirect_to root_path
end
private
def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end
def remember_token
cookies.signed[:remember_token] || [nil,nil]
end
end
*EDIT:*************************************************
I'm using the tutorial on:
http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users # Listing 9.12
Listing 9.12. Adding a signed_in_user before filter.
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:edit, :update]
.
.
.
private
def signed_in_user
redirect_to signin_path, notice: "Please sign in." unless signed_in?
end
end
When I included the helper in the SessionsController I received the message
undefined method `signed_in?' for #
Extracted source (around line #9):
<div>
<% if controller.signed_in? %> <----LINE 9
<%= link_to "Sign Out", signout_path, :method => :delete %>
<% else %>
<%= link_to "Sign IN" , signin_path %>
I included the Helper like this:
class SessionsController < ApplicationController
include SessionsHelper
I couldn't get this to work, so I copied the helper methods into SessionsController and the error went away.and now I'm having an issue with 9.12 where signed_in? is an unknown method. and it makes sense because signed_in? is in SessionsController via a helper. can the UserController access that function. I'm new to rails and confused.
thanks for all the feedback
EDIT:******************
Here is the ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery
include ActionView::Helpers::SessionsHelper
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
You're declaring your shared methods in the wrong place. signed_in? should be defined inside your ApplicationController, which is the shared base class for all your other controllers. There is, in essence, no way for you to do what you're trying to do. The UsersController can't access your SessionController's methods, nor should it be able to. That isn't how controllers work.
current_user, current_user=, and signed_in? all belong in your ApplicationController, not your SessionsController, because they're shared methods meant to be used by all your controllers which inherit from ApplicationController.
I figured out, I had a sessionhelper file from another project open and I was editing that one instead of the one associated with my current project. Thanks for the help.

Validations for Importing CSV data into MySql database in Rails 3.1?

i implemented the task of importing data from csv into MySQL database successfully. Now, my requirement is: i need to get error message with line number, if there is any mis match of data in csv file while importing.
This is my controller code:
**require 'csv' #at the top and followed by...
def load_csv
# no code
end
def import_csv
parsed_file = CSV.foreach(params[:csv].tempfile,:headers => true) do |row|
row = row.to_hash.with_indifferent_access
Institute.create!(row.to_hash.symbolize_keys)
redirect_to :action => :index
end
In my view/ load_csv.html.erb:
<%= form_for(:institute, :url => import_csv_institutes_path, :html => {:multipart => true}) do |f| %>
<div class="field">
<%= file_field_tag :csv %>
<%= f.submit 'Import' %>
</div>
<% end %>
These are the only two steps i used for importing. Model validations are working only for form and for csv, an error page displayed..
Please try to help me out.........................
Assign an error message to the flash[:notice] variable in the import_csv method. Do it before redirect.
http://guides.rubyonrails.org/action_controller_overview.html

Ruby on Rails: a weird no method error in my controller?

Here's what I got in my logs:
Started POST "/video_votes.437?type=up" for 127.0.0.1 at Fri Mar 18 01:11:14 -0700 2011
Processing by VideoVotesController#create as
Parameters: {"authenticity_token"=>"DLyDcc4MJxK7gk4URiyyjvsLLl9hjtDChAyQRGVawKg=", "type"=>"up"}
Completed in 83ms
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]):
app/controllers/video_votes_controller.rb:3:in `create'
I get this error when I click the button that calls on the create method.
Here's the code in my create method (note that line three is the #video = Video.find(params[:video_vote][:video_id]) line):
def create
#video = Video.find(params[:video_vote][:video_id])
#vote = #video.video_votes.new
if params[:type] = "up"
#vote.value = 1
else
#vote.value = -1
end
if #vote.save
respond_to do |format|
format.html { redirect_to #video }
format.js
end
else
respond_to do |format|
format.html { redirect_to #video }
format.js {render 'fail_create.js.erb'}
end
end
And here's my code for the button in my view that calls the create method:
<div id='voting_div'>
<%= button_to "+1", video_votes_path(video, :type=> "up"), :remote => true %>
<div id='vote_display'>
<p id='votes'><%= pluralize video.vote_sum, 'Votes' %></p>
</div>
<%= button_to "-1", video_votes_path(video, :type=> "down"), :remote => true %>
</div>
What's going on here? How do I fix this error?
You params hash is
{"authenticity_token"=>"DLyDcc4MJxK7gk4URiyyjvsLLl9hjtDChAyQRGVawKg=", "type"=>"up"}
In this hash there is no key called "video_vote" , so when you try to access params[:video_vote][:video_id], because params[:video_vote] is nil. it will throw this error.
Check your routes or if you need to "GET" more values with the button, because your params hash doesn't know about the "video_vote" key.