ruby-on-rails - 如何编写这些资源的路由?

标签 ruby-on-rails ruby routes nested-routes

对于我的 Rails 应用程序,关联如下:

  • 一个用户有多个书签,并且属于该用户。
  • 一个用户有很多 friend 。
  • 用户有很多提醒。
  • 某个用户有很多评论。
  • 一个书签有很多评论。
  • 评论属于用户并属于书签。
  • 友谊属于用户。
  • 提醒属于用户

我的routes.rb文件:

Rails.application.routes.draw do

  root 'welcome#index'
  get 'home', :to => 'home#index'
  get 'searchApis', :to => 'home#searchApis'

  devise_for :users, :controllers => { registrations: 'registrations' }

  resources :users, shallow: true do
    resources :bookmarks, except: :new
    resources :friendships, only: [:index, :show, :destroy]
    resources :reminders
  end

  resources :bookmarks, shallow: true do
    resources :comments
  end

end

我正确地写出这些路线吗?

当我rake paths时,我得到了bookmarks#index两次,所以我很困惑。其中一个的前缀是 bookmark,另一个是 bookmarks。为什么会发生这种情况?

根据我的理解,应用程序不需要查看索引中的所有书签,因为它们仅对创建它们的用户可见。但是,我希望用户的 friend 可以看到提醒。

如果可能的话,我希望得到清理路线的建议。我真的怀疑我这样做是否正确。

最佳答案

我对你的规范的解释:

#config/routes.rb
resources :users, only: [] do #-> show a user's collections (no edit)
   resources :bookmarks, shallow: true, except: [:new, :edit, :update]                 #-> url.com/bookmarks/:id
   resources :comments, :friendships, :reminders, shallow: true, only: [:index, :show] #-> url.com/comments/:id
end

resource :bookmarks, except: :index do #-> url.com/bookmarks/:id
   resources :comments #-> url.com/bookmarks/:bookmark_id/comments/:id -- should be scoped around current_user
end

对于评论 Controller ,请执行以下操作:

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
   def new
      @bookmark = Bookmark.find params[:bookmark_id]
      @comment  = @bookmark.comments.new
   end

   def create
      @bookmark     = Bookmark.find params[:bookmark_id]
      @comment      = @bookmark.comments.new bookmark_params
      @comment.user = current_user
      @comment.save
   end
end

不要制作welcomehome Controller ,你不需要它们。

您可以在应用程序 Controller 中放置副手操作:

#config/routes.rb
root                   'application#index'
get 'home',        to: 'application#home'
get 'search_apis', to: 'application#search_apis'

当然,这有点像 antipattern (您最终会使您的 ApplicationController 变得臃肿),但如果您在其他 Controller 中只有晦涩的“一次性”操作,那么您最适合使用上述内容。


此外,仅使用 snake_case URL 的 小写 - HTTP's spec确定所有 URL 应按小写处理:

Converting the scheme and host to lower case. The scheme and host components of the URL are case-insensitive. Most normalizers will convert them to lowercase. Example: → http://www.example.com/

虽然这仅适用于域/主机,但它也适用于 URL 本身。

关于ruby-on-rails - 如何编写这些资源的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34845845/

相关文章:

ruby-on-rails - rails Controller 的速率限制

ruby - Chef 库其他 Recipe 库依赖

php - 告诉 zend router 为每个 url 添加前缀

python - Flask 路由在 URL 中给出 404 float

ruby-on-rails - ActiveRecord 连接 - 仅返回精确匹配

ruby-on-rails - 如何按日期范围内的每个日期对对象进行分组

Ruby 的一元 * 运算符

asp.net-web-api - 访问 ASP.Net Web Api 中的查询字符串?

ruby-on-rails - 上传响应式背景图片

ruby - 在 ruby​​ 中没有四舍五入的 float 格式