ActiveRecord 无键关联
我有两个表/模型(用户、人口统计),它们具有松散的关系并共享一个公共列(电子邮件)。同一电子邮件可能有多个用户记录,但只有一个人口统计记录。
是否可以定义 has_one 和 has_many 关系并强制它使用电子邮件列而不是 id 进行连接?
谢谢, 斯科特·
P.S.如果重要的话,我正在使用 ActiveRecord 3.x
I have two tables/models (User, Demographic) which have a loose relationship and share a common column (email). There could be more than one User record with the same email, but there would only be a single demographic record.
Is it possible to define a has_one and has_many relationship and force it to use the email column for the join instead of id?
Thanks,
Scott
P.S. If it matters, I am using ActiveRecord 3.x
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能使用非唯一数据作为键,因为没有任何东西可以强制资源属于电子邮件地址的哪个实例。不过,您可以使用电子邮件作为外键,但它将返回具有该电子邮件地址的所有用户的人口统计信息。
要覆盖外键,请执行以下操作:
参考:http://api.rubyonrails.org/类/ActiveRecord/Associations/ClassMethods.html
You can't use non-unique data as a key as there is nothing to enforce which instance of the email address the resource belongs to. You can use the email as a foreign key though, but it will return the demographic for all users with that email address.
To override the foreign key do:
Reference: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html