Alexander Kuzmin
Alexander Kuzmin

Reputation: 1120

Better Rails file structure for big projects?

I always seem to get stuck with 40 different models in the same folder namespaced like post.rb, post_comment.rb, post_rating.rb etc etc. Is there any way to make something like modules in rails, namespacing away everything with posts to a separate directory? (This directory could include the different controllers and views too).

Rails Engines seems promising but maybe there's something else that I've missed?

I think it would make the project easier to overview and to enter as a new collaborator.

If you have opinions against, please tell!

Upvotes: 1

Views: 680

Answers (3)

Billy Chan
Billy Chan

Reputation: 24815

It seems your modelling has some problem.

A comment is a comment. A post can have comment, a photo can have comment. But it's definitely not good practice to have models like post_comment, photo_comment. Well, I only see "post_comment" in question, but I guess you name it for such reason.

You'll be busy to follow and work for these models with similar functionalities, and then their controller, their views. Same is true to "post_rating" etc.

I would not say 40+ models is too much. But seeing new Basecamp has 50+ models and Dispora has 30+ models without sub folders, it may worth a review on your app's architecture to cut some.

If you plan to use "comment", "rating" on others such as "photo", you can use the name directly, and plan associations, polymorphic, modules to DRY the code.

Upvotes: 1

jirikolarik
jirikolarik

Reputation: 1267

I use namespaces.

When you run command rails g scaffold blog/post, it'll generate Post under Blog namespace.

app/models/blog.rb

module Blog
  def self.table_name_prefix
    'blog_'
  end
end

app/models/blog/post.rb

class Blog::Post < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

app/models/blog/category.rb

class Blog::Category < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

Upvotes: 3

aren55555
aren55555

Reputation: 1717

As an example you can place all of your post_*.rb models into a posts folder. Make sure to rename each model within the folder with Posts::Post* ie class Posts::PostRating < ActiveRecord::Base

Rather than update all the models' Class references in your codebase, in my opinion it is likely just easier to leave them all in the models directory and deal with the agony of having a bloated models directory.

Relevant Readings:

Upvotes: 0

Related Questions