我在导入csv文件时遇到问题。我收到类似“Employee_attendances#index中的NameError”的错误。
模型
class EmployeeAttendance < ActiveRecord::Base
attr_accessible :date, :emp_id, :in_time, :out_time, :status
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
@employee_attendance = EmployeeAttendance.find_by_emp_id_and_date(row['employee_id'],row['date'].to_date.strftime("%Y-%m-%d")) || EmployeeAttendance.new
@employee_attendance.emp_id = row['emp_id']
@employee_attendance.in_time = row['in_time']
@employee_attendance.out_time = row['out_time']
@employee_attendance.status = row['status']
@employee_attendance.date = row['date']
@employee_attendance.save!
end
end
end
在控制器中
class EmployeeAttendancesController < ApplicationController
def index
end
def new
end
def create
end
def import
EmployeeAttendance.import(params[:file])
redirect_to EmployeeAttendance_path, notice: "Sucessfully Created."
end
end
在视图中(index.html.erb)
<% if flash[:notice].present? %>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:notice] %>
</div>
<% end %>
<div>
<h2>Employee Attendance</h2>
</div>
<%= form_tag import_employee_attendance_index_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import", :class => 'btn btn-primary' %>
<% end %>
它显示错误,例如“未定义的局部变量或方法`import_employee_attendance_index_path',用于#&lt;#:0xb30a8c88&gt;”
答案 0 :(得分:0)
我猜您尚未为方法routes
添加import
,请在routes.rb
resources :employee_attendances do
post 'import'
end
重新启动服务器,然后按照行
<%= form_tag import_employee_attendance_path, multipart: true do %>
答案 1 :(得分:0)
将此添加到您的路线文件中:
resources :employee_attendances do
collection do
post 'import'
end
end
或者这个:
resources :employee_attendances do
post 'import', on: :collection
end
并且要查看:
<%= form_tag import_employee_attendances_path, multipart: true do %>
由于