首页 > 解决方案 > 在rails中导入excel文件时如何在模型中传递参考ID

问题描述

我正在根据 excel 文件中的id列将数据从 excel 文件导入到两个不同的表中。
project与 one_to_many 关联并stage
stageone_to_many 关联,但在阶段表中导入数据task时我无法通过。project_id同样我想对task表做一列stage_id

阶段.rb

  belongs_to :project
  has_many :tasks, dependent: :destroy

  def self.import(file, project_id)
    accessible_attributes = ['task_name','planned_start_date', 'planned_end_date', 'actual_start_date', 'actual_end_date']


    spreadsheet = Roo::Spreadsheet.open(file)
    header = spreadsheet.row(1)
    i = 2
    last_row = spreadsheet.last_row

    (2..spreadsheet.last_row).each do |i|
        row = Hash[[header, spreadsheet.row(i)].transpose]
       if row['id'].is_a?(Integer) == true
        stage = Stage.new
        stage.attributes = row.to_hash.slice(*accessible_attributes)
        #stage.attributes = row.to_hash.merge(project_id: project_id).slice(*accessible_attributes) -> i tried this line also
        stage.save!


       elsif row['id'].to_s.split('').count == 3
        task = Task.new
        task.attributes = row.to_hash.slice(*accessible_attributes)
        task.save!
      end
    end
end

stage_controller.rb

  def import
    Stage.import(params[:file], params[:project_id])
    redirect_to project_path(@project), notice:"Projects imported. "
  end

index.html.erb

<h2>Import Project Activities</h2>

<%= form_tag import_project_stages_path(@project), multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import", :class=>"button warning" %>
<%end %>

我尝试了什么-在我添加的 stage.save 行之后-

Stage.update_all(project_id: 1) # this worked 
Stage.update_all(project_id: project_id) # this doesn't worked i don;t know why project_id is not accessible here. 

标签: ruby-on-railsexcelrubyrubygems

解决方案


stage.project_id = project_id在保存之前尝试类似的东西


推荐阅读