0

I have a rails app that works almost like a blog, and I use a tagging system to categorize the posts.

I need to add to some of the posts something similar to a "related posts" feature.

So for example if post 1 is related to post 4, at the end of the show action for post one I want to render an image of post 4 and at the same time at the end of post 4 an image of post 1.

My idea is to create a "link" model that has a HABTM relations with the post model, but I'm not sure if a "post" has many "links" trough "linkings" would be better. Both of the ideas seem to have the same result, so which approach should I prefer?

4

1 回答 1

1

HABTM 本质上非常简单,只有一个外键对加入模型的表。

通常has_many,当您需要向该连接关系添加其他属性时,和/或当您需要将连接视为它们自己的模型时,通常使用 through。

例如,在您的情况下,您可能希望链接按照它们创建的顺序出现。为此,您需要在关系上存储创建时间戳。为此,简单的 HABTM 连接表是不够的,因此您切换到has_many通过并创建一个Linking模型来封装连接。

要继续该示例,您还可以创建Linking一个一流的资源,并拥有一个页面,您可以在其中分别编辑/添加/删除它们Post

就个人而言,我has_many在大多数情况下总是使用 through。它对我来说感觉更干净(没有自动命名表魔法可以接受或覆盖,并且链接更加明显),而且我发现很多时候,连接关系确实应该成为一等公民。

于 2012-11-11T04:40:51.937 回答