Use case

Use case

Before to start

I?m thrilled to share with you our latest project: Fun Facts about Ruby ? Volume 1

Please feel free to spread the word and share this post! ?

Fun Facts about Ruby ? Volume 1

Fun Facts about Ruby ? Volume 1 is a collection of cards..

www.rubycademy.com

Thank you for your time!

Let?s take the example of a blog with the following models:

  • A post habtm tags
  • A tag habtm posts

habtm stands for has_and_belongs_to_many.

how is it represented in rails ?

Let?s assume that the Post and Tag models already exist.

This is the migration for the join table

And then the associations in models

Cool! That works!

Few months later, you want to order tags in each post for searching purposes.

HABTM to has_many :through

Why ?

In our case, has_many :through allows us to declare the join table as model. And so, in order to operate (filter, sort, allow, reject, etc..) at a join table level. By doing this, we?ll be able to store the rank of a tag in the post’s tag list directly in the join model.

Migration issue

A model needs a primary key to be retrieved. By convention rails uses the id column as primary key. The problem is that we’ve removed the id column from our join table (id: false). this makes sense because we just need the post_id and tag_id to retrieve a record.

But in order to use has_many :through, we need to add a primary key to the posts_tags table. So how to do so ?

Then in models

Voil !

May I have your attention please ??

Image for post

Feel free to subscribe here: www.rubycademy.com

Thank you for taking the time to read this post 🙂

Feel free to ?and share this medium post if it has been useful for you.

Here is a link to my last post entitled Regexp Implementation in Ruby .

No Responses

Write a response