user3376486
user3376486

Reputation: 33

Organizing namespaced and related models in Rails

I'm having a bit of trouble organizing a Rails project and its models regarding folder structure and conventions and I don't seem to find anything related to this anywhere.

Let's say I want to create a Cinema model, this Cinema has many Cinema::Location models and each Cinema::Locationhas many Cinema::Location::Movie screenings, on top of that each movie might have a Cinema::Location::Movie::Review, not to mention each review might have comments...

My folder structure would look something like this:

This is an organized solution, but at the same time, it doesn't look good, it's worse if we talk about the tables (cinema_location_movie_review_comment_replies).

One thing I could do is to organize the models like this: Cinema::Location for the location and Location::Movie for movies, Movie::Reviewfor reviews, etc.

Folder structure would look like this:

This solves the problem with the table names (location_movie or movie_review).

Are there any conventions regarding multi-level namespaced models?

Upvotes: 0

Views: 35

Answers (1)

jmschles
jmschles

Reputation: 274

Have you asked yourself why you're nesting your models at all? It looks to me like you're trying to shoehorn namespaces into performing logic that's better left to associations.

If you check out the ActiveRecord associations docs, you'll notice that in the first example, Book and Author are top-level models -- there's no mention of Book::Author or anything like that. There's your convention.

As your application grows more bigger and more complex, cases may arise where model namespacing is appropriate (say, resources specific to different user types), but I don't think it is here.

Upvotes: 1

Related Questions