Rails 4:我可以在一个浅资源中深度嵌套一个浅资源吗?
Rails 4: can I deep nest a shallow resource within another shallow resource?
在我的Rails4个app中,有五个模型:
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
资源添加到路由文件中,我正在考虑将其与 shallow: true
嵌套在 posts
资源中,这已经是一个浅资源,如下:
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 初学者,我可能会监督一些技术原因,这会使这种做法成为一种不好的做法,并在未来的应用程序开发方面造成重大问题吗?
是的,您的嵌套浅路由可以正常工作。此外,由于深度嵌套的资源很快变得很麻烦,因此需要使用浅层路由。所以,我认为如果您作为应用程序开发人员可以接受,那很好。
Jamis Buck 提出了一个好的经验法则 Rails 设计:
Resources should never be nested more than 1 level deep.
所以,我不认为你在这里监督任何事情。如果适合您,您可以使用那些浅路线。
在我的Rails4个app中,有五个模型:
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
资源添加到路由文件中,我正在考虑将其与 shallow: true
嵌套在 posts
资源中,这已经是一个浅资源,如下:
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 初学者,我可能会监督一些技术原因,这会使这种做法成为一种不好的做法,并在未来的应用程序开发方面造成重大问题吗?
是的,您的嵌套浅路由可以正常工作。此外,由于深度嵌套的资源很快变得很麻烦,因此需要使用浅层路由。所以,我认为如果您作为应用程序开发人员可以接受,那很好。
Jamis Buck 提出了一个好的经验法则 Rails 设计:
Resources should never be nested more than 1 level deep.
所以,我不认为你在这里监督任何事情。如果适合您,您可以使用那些浅路线。