【问题标题】:How to retrieve column value from table1 and keep it in table2's column?如何从 table1 中检索列值并将其保存在 table2 的列中?
【发布时间】:2015-04-08 10:17:44
【问题描述】:

表_1:

ID |   Name    | Address
1  |  prakash  | 2-107, NY
2  |  rakesh   | 2-109/a, NY

表_2:

emp_ID| Name    | Designation
   ?  | Prakash | Software Developer
   ?  | Rakesh  | Software Tester

通过使用 table-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

【问题讨论】:

  • 你的 csv 文件有标题吗?
  • 不,我没有使用@shivam
  • 澄清一下,这两个 CSV.foreach 是同一个文件的一部分吗?

标签: mysql ruby csv activerecord rubygems


【解决方案1】:

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

【讨论】:

  • 向我推荐一些链接和书籍,以将我的名称从 Beginner 更改为 Programmer
  • 我自己也是一名学习者。最好的建议是在卡住时继续编写代码和 google/SO。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多