如何从表 1 中检索列值并将其保存在表 2 的列中?

How to retrieve column value from table1 and keep it in table2's column?

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

通过使用 table-2 中的名称列,我需要从 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

假设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