2015-04-08 20 views
-1

TABLE_1:如何从table1中检索列值并将其保存在table2的列中?

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中使用的名称列,我需要从表1中的ID,并将其放置在表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

不CSV文件有头? – shivam

+0

不,我没有使用@shivam –

+0

只是为了清楚,这些都是'CSV.foreach'部分的同一个文件? – shivam

回答

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 
+0

非常感谢你@shivam .., –

+0

建议我将一些链接和书籍从__Beginner__ –

+0

改为__Programmer__我自己是一名学习者。我能建议的最好的办法是继续写代码和谷歌/ SO卡住了。 :) – shivam

相关问题