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?

TopperH
  • 2,183
  • 18
  • 33

1 Answers1

1

HABTM is by nature very simple, with just a table of foreign key pairs joining models.

Typically has_many through is used when you need to add additional attributes to that join relation, and/or when you need to treat the joins as their own model.

In your case, for example, you might want the links to appear in the order that they were created. For this to happen you'd need to store the create timestamp on the relationship. For this, the simple HABTM join table is not enough, so you switch to has_many through and create a Linking model to encapsulate the join.

To continue the example, you might also make Linking a first-class resource, and have a page where you can edit/add/remove them separately from either linked Post.

Personally I've always used has_many through in the majority of cases. It just feels cleaner to me (no auto-naming table magic to accept or override, and the linking is more visible), and I find that very often, join relationships do deserve to be first class citizens.

numbers1311407
  • 33,686
  • 9
  • 90
  • 92