1

在我的Rails 4的应用程序中,有五款车型:Rails 4:我可以在另一个浅层资源内嵌入浅层资源吗?

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 

目前,我的结构我的资源如下:

Rails.application.routes.draw do 

    root to: 'pages#home' 

    devise_for :users, :path => 'account' 

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

end 

现在,我需要将comments资源添加到路由文件和我正在考虑的posts资源,这已经是一个浅的资源内的shallow: true嵌套,如下所示:

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 

我相信这在技术上是可行的,但我不确定这会被认为是好的或不好的做法。

特别是因为,根据我在Rails Guides中的了解,浅层嵌套的主要目的是避免深层嵌套。

换句话说,我是否有技术上的原因可能会作为Rails初学者进行监督,这会使得这种做法成为一种不好的做法,并且会在将来开发应用程序时引发重大问题?

回答

1

是的,你的嵌套浅路由将正常工作。此外,由于深度嵌套资源很快变得繁琐,因此使用浅层路由。所以,我认为如果你作为一个应用程序开发人员可以,那就好了。

了Jamis巴克提出拇指良好的Rails设计的原则:

资源不应该被嵌套超过10级深。

所以,我不认为你在这里监督任何事情。如果这些工作适合你,你可以使用这些浅层路线。

+1

谢谢,你的帮助总是非常有用和赞赏。 –

+0

你是最欢迎的:)你正在学习快:)保持它:) –

+1

谢谢;)我看到你在堆栈溢出以及很好,祝贺! –

相关问题