在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. 
阿迪亚·帕里克

stage.project_id = project_id在保存之前尝试类似的操作

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章