Rails foreign key column name convention for a unary many-many relation

瘦欲@ 提交于 2020-01-15 08:28:09

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/9555984/rails-foreign-key-column-name-convention-for-a-unary-many-many-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!