ruby-on-rails - 在rails中导入excel文件时如何在模型中传递参考ID
问题描述
我正在根据 excel 文件中的id
列将数据从 excel 文件导入到两个不同的表中。
project
与 one_to_many 关联并stage
与
stage
one_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
在保存之前尝试类似的东西
推荐阅读
- ios - 在 sizeToFit 之后将字形对齐到 UITextView 的顶部
- json - 查询 Firebase 数据库 Swift
- javascript - Firebase 从 uid 加载所有数据
- php - 如何在打开某些 url 时设置它不被 wordpress 处理
- ansible - Ansible azure_rm_virtualmachine_extension 模块失败并出现异常
- python - 如何使用 python 在内存中找到 00000000,就像 C 使用 while != 00000000 一样
- angular - ForEach 内的 Angular2 延迟
- c# - 发生“System.ArgumentOutOfRangeException”类型的未处理异常
- reactjs - 测试通过但覆盖率没有更新 - Jest Enzyme - React JS
- ibm-watson - 使用 Watson 作为测试工具