2017-03-19 43 views
0

请不要使用默认表ID作为表的主键时,如何引用表?我创建了两个表,其中一个以电子邮件作为主键,我希望将此表电子邮件作为另一个表中的外键。请问我怎样才能做到这一点?添加对表的引用

回答

0

您可以创建表,电子邮件作为主键是这样的:

create_table :users, id: false do |t| 
    t.string :email, primary_key: true 
    t.string :name 

    t.timestamps 
end 

create_table :posts do |t| 
    t.string :title 
    t.text :body 
    t.string :user_email 

    t.timestamps 
end 

,并定义你的模型是这样的:

class User < ActiveRecord::Base 
    self.primary_key = 'email' 
    has_many :posts, foreign_key: :user_email 
end 

class Post < ActiveRecord::Base 
    belongs_to :user, foreign_key: :user_email 
end 

这就是所有你需要做的。您也可以将id保留为User模型的主键,但使用email作为外键 - 这可能是处理模型的更简单的方法。

+1

ok @ i.lavrov。感谢你的回答 –