我正在根据 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
在保存之前尝试类似的操作
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句