Rails: If Foo has_many: bars, all: bars should belong to Foo?

I am working on an application in which there are many photos that are provided by users. The most important goal of the application is the aspect of sharing photos.

It is sometimes useful to create recognized "collections" of photographs. Thus, it is easy enough in ActiveRecord: Collection has_many :photos and Photo belongs_to :collection .

The question I have is that for a “regular” photo that does not belong to a special collection, I have to:

a. Do not belong to any collection at all. i.e.: photo.collection == nil

-or-

C. Create a shared community collection that contains each photo. , i.e. By default photo.collection == 'Community'

I am also considering whether this should be a HABTM relationship.

Feedback will be greatly appreciated!

+4
source share
3 answers

Actually, it depends on what you are going to do with your uncleared photos. If you want to display unsaved photos with the same action that you use to display the collection, then you will want to get this shared collection. Otherwise, I would leave it zero; I don’t like mixing “seed” data with user data in one table (what would you do with an “unconfirmed” collection) - it's too easy to accidentally erase your user data when you visit again.

Should there be a HABTM relationship? Again, it depends on how you want to use it. If you have a good chance that the photos will belong to several collections, go for it.

And what I saw was mentioned here that I wouldn’t do it: adding the attribute “ptype” to talk about single games from the collected photos (waste of database space - can you already get this information by calling photo.collection_id.nil? ); and using polymorphic models (you don’t want single-element photographs to behave completely different, I suppose that's why this added complexity for little use).

Named scopes, however, are a great idea and will be especially useful if you don't have a "uncollected" collection to find your singlets:

 #Apologies for the Rails 2.3 code - it what I know... named_scope :singletons, {:conditions => {:collection_id => nil}} 

Or HABTM version:

 named_scope :singletons, lambda { {:conditions => ['NOT EXISTS (SELECT * FROM collections_photos WHERE photo_id = ?)', self.id]} } 

Hope this helps!

+7
source

What about using the ptype attribute? You can have photo.ptype = 'collection' or photo.ptype = 'single'. This way you can identify each photo with this type. In addition, you can make it even more elegant by using the area in photos and specifying the area of ​​the collection_photos or single_photos.

Another possibility is polymorphic models. You have a photo model and a collection of Photo and singlePhoto that use it.

+1
source

I would set the collection property only when it belonged to the collection. Just make sure your view code can handle this case.

+1
source

Source: https://habr.com/ru/post/1340879/


All Articles