Rails的外键列名约定一元多对多关系 [英] Rails foreign key column name convention for a unary many-many relation

查看:559
本文介绍了Rails的外键列名约定一元多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果有一个用户表和上岗表,职位表中有一个名为user_ID的一个外键列,根据轨道约定。我的问题出现时,我有一个用户表和我试图使关系是一元多对多(很多买家可以通知许多卖家,买家和卖家都用户)。现在,通知是连接表,必须包含外键USER_ID和user_ID的根据命名外键的轨道公约存储买卖双方身份证,但显然这无法做到的。谁能告诉我如何命名FK列一元多对多的关系,什么是轨道存取方法这样一种关系?

解决方案

 班的通知
     belongs_to的:卖方,将class_name:用户
     belongs_to的买方,将class_name:用户
结束
 

和您的通知表的外键应该是 seller_id buyer_id 。 该foreign_keys的名称由协会的名称(卖方和买方在这里)的推断。

I know that if there is a "users" table and a "posts" table, the posts table has a foreign key column named 'user_id', according to the rails convention. My problem arises when I have a "users" table and the relation that i am trying to make is unary many-many(many buyers can notify many sellers, buyers and sellers are both "users"). Now "notifications" is the join table, that must contain the foreign keys "user_id" and "user_id" for storing the buyer and seller ids according to the rails convention of naming foreign keys, but obviously this cannot be done. Can someone tell me how to name F.K columns in a unary many-many relation and what are the rails accessor methods for such a relation?

解决方案

class Notification
     belongs_to :seller, class_name: "User"
     belongs_to :buyer, class_name: "User"
end

And your foreign keys in the notifications table should be seller_id and buyer_id. The names of the foreign_keys are inferred by the name of the associations (seller and buyer here).

这篇关于Rails的外键列名约定一元多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆