TABLE_1:
ID | Name | Address
1 | prakash | 2-107, NY
2 | rakesh | 2-109/a, NY
TABLE_2:
emp_ID| Name | Designation
? | Prakash | Software Developer
? | Rakesh | Software Tester
通过使用表-2中的Name列,我需要从table-1获取id并将其放在table-2中。
require 'csv'
load 'dbconnection.rb'
require 'activerecord'
class Employee<ActiveRecord::Base
end
class Designation<ActiveRecord::Base
end
#Employee Table Data Insertion
CSV.foreach("C:/Users/modi/Desktop/employee.csv") do |row|
Employee.create!(
# ID will be auto increement
:name => row[0],
:address => row[1],
)
end
#Designation Table Data Insertion
CSV.foreach('C:/Users/modi/Desktop/designation.csv') do |row|
Designation.create!(
:Emp_id #Here we need to get the id value from the Employee Table
:name => row[0],
:designation=>row[1]
)
end
答案 0 :(得分:0)
假设Employee
不包含大量数据,您可以这样做:
employees = Employee.all
CSV.foreach('C:/Users/modi/Desktop/designation.csv') do |row|
Designation.create!(
:Emp_id => employees.detect { |emp| emp.name == row[0] }.id # handle nil case
:name => row[0],
:designation=>row[1]
)
end