2016-12-17 2 views
1

xls 파일의 데이터를 내 레일 5 psql 데이터베이스에 추가하는 방법을 알아 내려고합니다.레일 5- 데이터를 xls 파일에서 데이터베이스로 가져 오는 방법

나는 GoRails 튜토리얼을 따라 가려고했지만, 응용 프로그램의 어딘가에서 만든 CSV 파일을 사용하기 때문에 자습서를 작성하기 때문에 관련성이 없어집니다. xsl 데이터를 csv 데이터로 변환하여 튜토리얼을 따라하는 법을 모르겠습니다.

각 튜토리얼을 시도해 보았습니다. 나는 그들 중 누구도 일할 수 없습니다.

나는 this tutorialthis onethis one을 시도했습니다. 나는 그들 중 누구도 일할 수 없습니다.

첫 번째 튜토리얼에서 블로그에 게시 한 질문에 대한 답변은 게시물에서 설명하지 않은 단계를 수행한다고 말합니다. 단계별 지침에 따라 단계의 틈을 메꿔야한다고 생각하지 않습니다.

나는 이것을 SO post에서 작동시키려는 나의 시도를 개략적으로 설명했다. xls 업로드 작업을 수행하는 데 도움을 찾을 수 없었습니다. 그래서 저는 처음으로 SO 게시물이 제안 된 솔루션을 구현하기 위해 만든 다양한 시도와 함께 매우 길어 졌기 때문에 다시 도움 요청을 준비하고 있습니다.

나는이 :

class Randd::Field < ApplicationRecord 

    require 'csv' 


    # def self.import(file) 
    #  CSV.foreach(file.path, headers: true) do | row | 
    #   Randd::Field.create! row.to_hash 
    #  end 
    # end 

    def self.create(file) 
    CSV.foreach(file.path, headers: true) do |row| 

     randd_field_hash = row.to_hash # exclude the price field 
     randd_field = Randd::Field.where(id: randd_field_hash["id"]) 

     if randd_field.count == 1 
     randd_field.first.update_attributes(randd_field_hash) 
     else 
     Randd::Field.create! row.to_hash#(randd_field_hash) 
     end # end if !product.nil? 
    end # end CSV.foreach 
    end # end self.import(file) 

먼저 직감 :이 모델에서, 나는 'CSV'를 요구하고있다. 'xls'또는 다른 곳에서 쉼표로 구분 된 값 목록을 실제로 가져올 필요가 없다는 점을 요구해야합니까?

Routes.rb

namespace :randd do 
    resources :fields do 
     collection do 
     post :create 
     end 
    end 
    end 

컨트롤러 :

class Randd::FieldsController < ApplicationController 

def index 
    @randd_fields = Randd::Field.all 
end 

def new 
    @field = Randd::Field.new 
end 

def create 
    # @field = Randd::Field.new(randd_field_params) 
    Randd::Field.create(params[:randd_field][:file]) 
    redirect_to action: "index", notice: "Data imported" 
end 

def show 
    redirect_to action: "index" 
end 

인덱스보기 : 쇼 위에 나는이를 얻기 위해 사용하려고하는 모든 다양한 옵션을 표시

<table class="table table-bordered"> 
    <tr> 
     <td> <h5>Title</h5> </td> 
     <td> <h5>Reference (ANZ)</h5> </td> 
     <td> <h5>Added</h5> </td> 

    <%# if policy(@package_ips).update? %> 
     <td> <h5>Manage this asset</h5></td> 
    <%# end %> 

    </tr> 
     <% @randd_fields.each do | field | %> 
     <td> <%= field.title %> </td> 
     <td> <%= field.anz_reference %> </td> 
     <td> <%= field.created_at.try(:strftime, '%e %B %Y') %> </td> 
     <% end %> 
    </tr> 
    </table> 

주석으로 구성 요소 일하다.

# def import 
# # byebug 
# # Randd::Field.import(params[:file]) 
# # Randd::Field.create(params[:randd_field]['file']) 
# # redirect_to action: "index", notice: "Data imported" 
# end 

private 
def randd_field_params 
    params.fetch(:randd_field, {}).permit(:title, :anz_reference) 
end 

end 

내 양식이 있습니다 말한다 내 생성 활동의

NoMethodError - undefined method `[]' for nil:NilClass: 
    app/controllers/randd/fields_controller.rb:13:in `create' 

행 13 :

Randd::Field.create(params[:randd_field][:file]) 

<%#= simple_form_for (@field), multipart: true do |f| %> 
<%= simple_form_for @field, multipart: true do |f| %> 
    <%= f.error_notification %> 

    <div class="form-inputs" style="margin-bottom: 50px"> 
    <div class="row"> 
     <div class="col-md-12"> 
     <div class="form_title">Research Field Codes</div> 
     </div> 
    </div> 

    <div class="row"> 
     <div class="col-md-12"> 
     <%= f.file_field :file %> 
     </div> 
    </div> 
    </div> 

    <div class="row"> 
    <div class="col-md-10 col-md-offset-1" style="margin-top: 50px"> 
     <div class="form-actions"> 
     <%= f.button :submit %> 
     </div> 
    </div> 
    </div> 
<% end %> 

이러한 시도에서 발생하는 오류 메시지가 말한다

다음 직감 : 내 리소스는 n입니다. ested. Randd는 최상위 레벨이고 필드는 하위 레벨입니다.

모델이 호출된다

class Randd::Field < ApplicationRecord 

제어기가 호출된다

class Randd::FieldsController < ApplicationController 

컨트롤러 내의 허용 PARAMS과 같이 정의된다 :

params.fetch(:randd_field, {}).permit(:title, :anz_reference) 

형태는이 개구를 사용 줄 :

01 오류 메시지에 강조 23,767,

라인이 있습니다

Randd::Field.create(params[:randd_field][:file]) 

나는 문제가이 장소의 일부 randd_field를 사용하여 단지 형태로 @field 함께 할 수있는 뭔가가 궁금해? @randd_field로 변경하려고하면 양식이 작동하지 않으며 완전한, 정확한 형식으로 네임 스페이스를 사용하는 방법에 대한 루비 또는 레일 규칙을 어디에서 찾을 수 있는지 알지 못합니다.

누구든지 여기서 무엇이 잘못된지 볼 수 있습니까? 또는 자습서에 대한 참조가있는 사람은 누락 된 단계가 무엇인지 추측하지 않거나 .csv 파일 대신 xls로 변환하는 방법을 사용하고 있습니까?

답변

0

사용할 수있는 몇 가지 루비 xls 파서가 있습니다. 크릭, 단순 스프레드 시트 및 Roo.

관련 문제