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
restaurant.lounge_photos
and receive only the lounge photos, but also be able to call
restaurant.food_photos
and receive just the food photos.
The two methods I can think of are:
to use multiple joins table, and a has_many to has_one relationship for each type of photo.
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.
- Make association with
restaurant
andphoto
class Restaurant < ActiveRecord::Base has_many :photos end class Photo < ActiveRecord::Base belongs_to :restaurant end
- Then you have to use STI in
Photo
model. The reason is that you have almost all fields are common forlounge_photos
andfood_photos
.
OR
Using scope directly you can differentiate it and achieve your goal.
For more details of use STI you can refer this link.