0

my current project is making a diary app, where users can log in and post their articles to which comments can be linked. So the very natural way of implementing this project is something like

resources :users do
  resources :articles do
    resources :comments
  end
end

Class User < ActiveRecord::Base
   has_many :articles
end

Class Article < ActiveRecord::Base
    belongs_to :user
    has_many :comments
end

Class Comment < ActiveRecord::Base
   belongs_to :article
end

However, rails guide says the resources should never be nested more than one level. With this relationship, how can I avoid using two-level nested resources?

1
  • 2
    The rails guide also tells you how to avoid this.
    – j-dexx
    Feb 10, 2015 at 12:01

2 Answers 2

2

Check out Rails Guides: http://guides.rubyonrails.org/routing.html#nested-resources part 2.7.2 Shallow Nesting. E.g.:

resources :articles do
  resources :comments, shallow: true
end
0
1

To avoid this you need to use Shallow Nesting. The rails guide has the complete tutorial on how to do that. Also there are many questions on stackoverflow related to that. Here are some links:

http://guides.rubyonrails.org/routing.html#nested-resources

When using shallow routes, different routes require different form_for arguments

Rails 4 [Best practices] Nested resources and shallow: true

https://railsforum.com/topic/1431-best-practices-nested-resources-and-shallow-true/

If you still get any issue implementing that then you should ask on stackoverflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.