我大致与MickJ认同,虽然已经建立的公司和用户模型/桌(这显然在每个ID列)我会做它:
create_table "companies" do |t|
t.string "name"
...
end
create_table "positions" do |t|
t.references "user"
t.references "company"
...
end
create_table "followings" do |t|
t.references "user"
t.references "company"
...
end
型号:
class User
has_many :positions
has_many :followings
end
class Company
has_many :positions
has_many :followings
end
class Position
belongs_to :user
belongs_to :company
end
class Following
belongs_to :user
belongs_to :company
end
你可以做参考公司从位置:
position = Position.first
puts position.company.name
或通过类似的用户
user = User.first
user.positions.each do |position|
puts position.company.name
end
- EDIT1:
从位置提取的公司名称到一个单独的表你最好关闭写一个小耙子任务 - 是这样的:
Position.all.each do |position|
company = Company.find_or_initialize_by_name(position.company_name)
position.company_id = company.id
position.save
end
然后你可能希望编写一个迁移以从职位表中删除公司名称列...只是为了保持整洁。
“我如何安全地从我的职位表中提取公司专栏并保留职位/公司关系?”。只需创建一个名为company的新表,其中包含'company_id'和'company'列。然后只需从“职位”表中删除公司专栏。 – MickJ
好的,但我需要的是其他所有的位置ID。有没有一个简单的低风险的方式呢? – keypulsations
为position_id添加一列,并为其创建一个dbs序列。写一个小脚本或一个过程,以从序列中填充它。然后一旦它完全填充,添加约束它是唯一的。 – MickJ