0

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:

  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?

Jack Pincus
  • 61
  • 1
  • 6

2 Answers2

1

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

  1. Make association with restaurant and photo
class Restaurant < ActiveRecord::Base
 has_many :photos
end

class Photo < ActiveRecord::Base
 belongs_to :restaurant
end
  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.

Kishor Vyavahare
  • 799
  • 1
  • 8
  • 15
0

This is one way, using a type column

has_many :food_photos, 
         class_name: 'Photo', 
         foreign_key: :restaurant_id, 
         -> { where(type: 'food') }

has_many :lounge_photos, 
         class_name: 'Photo', 
         foreign_key: :restaurant_id, 
         -> { where(type: 'lounge') }
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54