1

In my Rails 4 app, there are five models:

class User < ActiveRecord::Base
  has_many :administrations
  has_many :calendars, through: :administrations
end

class Calendar < ActiveRecord::Base
  has_many :administrations
  has_many :users, through: :administrations
  has_many :posts
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Post < ActiveRecord::Base
  belongs_to :calendar
end

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

Currently, I structured my resources as follows:

Rails.application.routes.draw do

  root to: 'pages#home'

  devise_for :users, :path => 'account'

  resources :calendars do
    resources :posts, shallow: true
  end

end

Now, I need to add the comments resource to the route file and I am considering nesting it with shallow: true within the posts resource, which is already a shallow resource, as follows:

Rails.application.routes.draw do

  root to: 'pages#home'

  devise_for :users, :path => 'account'

  resources :calendars do
    resources :posts, shallow: true do
      resources :comments, shallow: true
    end
  end

end

I believe this is technically possible, but I am not sure this would be considered a good or bad practice.

Especially since, from what I understand in the Rails Guides, shallow nesting's main purpose is to avoid deep nesting.

In other words, are there technical reasons I may be overseeing as a Rails beginner that would make this a bad practice and cause significant problems in the future regarding the development of the app?

Thibaud Clement
  • 6,607
  • 10
  • 50
  • 103

1 Answers1

1

Yes, your nested shallow routing will work fine. Also, as deeply-nested resources quickly become cumbersome, hence comes the use of shallow routing. So, I think it is fine if you as an application developer is okay with that.

Jamis Buck proposes a rule of thumb for good Rails design:

Resources should never be nested more than 1 level deep.

So, I don't think you are overseeing anything here. You can use those shallow routes if those work for you.

K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110