简体   繁体   English

在Rails中的一个名为has_many的关系中,“单数”侧如何从“许多”侧访问记录?

[英]In a belongs_to has_many relationship in Rails, how does the 'singlular' side access records from the 'many' side?

It was my understanding that all keys are stored on the 'many' side, ie: if a user has many posts, and posts belong to only one user, foreign keys associating which user "owns" which which post exist only in the post object. 据我了解,所有密钥都存储在“许多”侧,即:如果用户有很多帖子,而帖子仅属于一个用户,则外键将哪些用户“拥有”哪个帖子仅存在于帖子对象中。

Yet, in my users controller, I can still create a user show page which lists all posts by looping through 'user.posts'. 但是,在我的用户控制器中,我仍然可以创建一个用户显示页面,该页面通过循环'user.posts'列出所有帖子。

How is this possible? 这怎么可能?

Thanks in advance. 提前致谢。

Edit: one caveat, I'm using MongoDB / Mongoid, not sure how this pans out with Active Record. 编辑:一个警告,我正在使用MongoDB / Mongoid,不确定如何通过Active Record进行同步。

The model with belongs_to part holds the column for reference, user_id in your situation. 带有belongs_to部分的模型在您的情况下保留供参考的列user_id

The model with has_many part queries the table, where belongs_to is, to get all references models. 具有has_many部分的模型查询该表所在的表belongs_to ,以获取所有引用模型。

Hope it helped you! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM