[英]Rails: foreign keys - how does the DB table looks like?
我在堆栈溢出时在这里找到了这个例子:
class User < ActiveRecord::Base
has_many :winners, class_name: "Competition", foreign_key: "competition_id"
end
class Competition < ActiveRecord::Base
belongs_to :winner, class_name: "User", foreign_key: "winner_id"
end
在这种情况下,“has_many: winners ”或“belongs_to: winner ”究竟是什么?
用户表中是否有“competition_id”列和比赛表中的“winner_id”列?
问候
表格看起来像:
users:
id: integer,
# other fields - name, email etc.
competitions:
id: integer,
winner_id: integer,
# other fields - name, place etc.
当有人使用获胜者 has_many 关联时,例如:
User.find(3).winners
它会做一个查询,结果是这样的:
SELECT * FROM competitions WHERE winner_id = 3 # the 3 here comes from the user's id
当有人使用获胜者belongs_to关联时,例如:
Competition.find(4).winner
它会做一个查询,结果是这样的:
SELECT * FROM users WHERE id = 1 # the 1 here has come from the winner_id on the competition record
获奖者协会的名字可能很糟糕; won_competitions 可能是一个更好的名字。
更多阅读: https : //guides.rubyonrails.org/association_basics.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.