Skip to content
Advertisement

rails multiple has_many relationships between the same models

I’m trying to figure out the best way to model a many-to-one relationship in rails where there are multiple scopes to the relationship.

An example would be a restaurant has-many photos. I want to be able to call

and receive only the lounge photos, but also be able to call

and receive just the food photos.

The two methods I can think of are:

  1. to use multiple joins table, and a has_many to has_one relationship for each type of photo.

  2. to add a ‘type’ attribute to the photo model and write a scoping method.

Both of these seem a bit clunky to me. Is there a better solution here?

Advertisement

Answer

I think you have to go has_many and Single Table Inheritance(STI), as follow.

  1. Make association with restaurant and photo
  1. Then you have to use STI in Photo model. The reason is that you have almost all fields are common for lounge_photos and food_photos.

OR

Using scope directly you can differentiate it and achieve your goal.

For more details of use STI you can refer this link.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement