검색결과 리스트
import csv에 해당되는 글 1건
- 2016.12.08 [Rails] import CSV 파일
1.routes.rb에 import path를 추가한다.
resources 'wifi_each_info', controller: 'device/wifi_settings/wifi_each_info' do
collection { post:import} #post로 추가한다.
end
2.view 에서 하기와 같이 추가
<%= form_tag(import_wifi_each_info_index_path, multipart:true) do %>
<%= file_field_tag :file %>
<%= submit_tag "Import CSV" %>
<% end %>
이때 file_field와 file_field_tag 는 기능상의 차이가 없다!!
3. controller에서 model을 호출한다.
def import
logger.debug "controller====#{params.inspect}"
if params[:file].present?
logger.debug "controller====#{params[:file].original_filename}"
DeviceWifiInfo.import(params[:file])
redirect_to wifi_common_index_path, notice: I18n.t('table.label.wifi_settings.each_info.completed_csv')
else
redirect_to wifi_common_index_path, alert: I18n.t('table.label.wifi_settings.each_info.failed_csv')
end
end
4. model에서 import를 구현한다.
def self.import(file)
logger.debug "====model = #{file.inspect}"
logger.debug "self.import"
CSV.foreach(file.path, headers: true, :encoding => 'ISO-8859-1') do |row|
logger.debug "===#{row.inspect}"
#1 create wifi infi not considering duplicate
if row["DHCP"] == "1" #row안에 있는 속성은 ""으로 묶어서 읽는다. 속성은 csv 헤더에서 읽어온다
dhcp = true
logger.debug "dhcp true"
else
dhcp = false
logger.debug "dhcp false"
end
wifi_info_new = DeviceWifiInfo.new(dhcp: dhcp,static_ip: row["static_ip"], static_subnet: row["static_subnet"],
static_gateway: row["static_gateway"], account_id: row["account_id"], account_password: row["account_password"],
serial_id: row["serial_id"])
wifi_info_new.save
end
end
end
RECENT COMMENT