Rails 协会 - has_many => :通过 - 但型号相同
我想做的事情:
我有一个博客,想在主帖子下方显示相关帖子。
class Post < ActiveRecord::Base
has_many :related_posts
has_many :posts, :through => :related_posts
end
然后在连接模型/表中
class RelatedPost < ActiveRecord::Base
belongs_to :post
end
当然有一个名为 lated_posts
的表,其中有两个 post_id
列。
显然这有几个缺陷,我只是不确定如何使这个关联在 Rails 中工作。
What I am trying to do:
I have a blog and want to show related posts below the main post.
class Post < ActiveRecord::Base
has_many :related_posts
has_many :posts, :through => :related_posts
end
And then in the join model/table
class RelatedPost < ActiveRecord::Base
belongs_to :post
end
And of course there is a table called related_posts
with two post_id
columns.
Obviously there are several flaws with this, I'm just not sure how to make this association work in Rails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个有趣的问题。
我刚刚为您的用例创建了一个工作应用程序。
post.lated_posts 将为您提供与帖子相关的所有帖子,而 post.inverse_lated_posts 将为您提供与帖子相关的所有帖子。
这是我的模型的样子:
我的架构:
这是演示关系的控制台会话的转储。
That was an interesting question.
I just created a working app for your use case.
post.related_posts will give you all posts related from post, while post.inverse_related_posts will give you all posts related to post.
Here's what my models look like:
My schema:
Here's a dump of a console session that demonstrating the relationship.
您正在寻找自我参照关联。
我建议您在这里获取灵感。
You're looking for self referential association.
I suggest you take inspiration here.