[英]how to pass reference id in model while importing excel file in rails
我正在根据 excel 文件中的id
列将 excel 文件中的数据导入两个不同的表中。
project
与stage
有 one_to_many 关联,并且
stage
与task
有 one_to_many 关联,但在 stage 表中导入数据时我无法传递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
索引.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
不清楚您是在将其 id 传递给方法之前还是之后创建project
。 您只需要检查数据库中是否存在具有该project_id
的项目,如果没有则创建一个。 此外, params[:project_id]
在从params
获取它时可能由于错误而无法工作,或者,如果它没有被发送(作为nil
发送),并且如果它不存在,你必须创建一个新的或者return
从方法。 此外,您可以返回stage
并将其分配给 controller 中的project
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.