【问题标题】:Rails 4: can I deep nest a shallow resource within another shallow resource?Rails 4:我可以在另一个浅层资源中深层嵌套一个浅层资源吗?
【发布时间】:2015-11-30 22:03:39
【问题描述】:

在我的 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 资源添加到路由文件中,我正在考虑将其与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 初学者,我是否有技术原因可能会导致这种做法成为一种不好的做法,并在未来对应用程序的开发造成重大问题?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model-view-controller routes nested-resources


    【解决方案1】:

    是的,您的嵌套浅层路由可以正常工作。此外,随着深度嵌套的资源很快变得繁琐,因此使用了浅层路由。所以,我认为如果您作为应用程序开发人员可以接受这一点。

    Jamis Buck 提出了良好 Rails 设计的经验法则:

    资源的嵌套深度不得超过 1 级。

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

    【讨论】:

    • 谢谢,您的帮助总是非常有用和感激。
    • 不客气 :) 你学得很快 :) 继续努力 :)
    • 谢谢 ;) 我看到你在 Stack Overflow 上也做得很好,恭喜!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2014-03-19
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多