我是 Rails 新手,我想要一些关于我的路线和正确的路由逻辑的建议。我正在开发一个非常简单的应用程序,用户可以在其中发布列表。用户(设计模型)有很多列表,并且该列表属于一个用户。我的列表中有一个 user_id:integer 。当用户成功登录时,我希望他们在相应的路线页面上看到他们的列表。我像这样创建了嵌套路由:
devise_for :users, :paths => 'users'
resource :users do
resource :lists
end
这是我的 rake 路线的输出
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
users_lists POST /users/lists(.:format) lists#create
new_users_lists GET /users/lists/new(.:format) lists#new
edit_users_lists GET /users/lists/edit(.:format) lists#edit
GET /users/lists(.:format) lists#show
PATCH /users/lists(.:format) lists#update
PUT /users/lists(.:format) lists#update
DELETE /users/lists(.:format) lists#destroy
users POST /users(.:format) users#create
new_users GET /users/new(.:format) users#new
edit_users GET /users/edit(.:format) users#edit
GET /users(.:format) users#show
PATCH /users(.:format) users#update
PUT /users(.:format) users#update
DELETE /users(.:format) users#destroy
root GET / static_pages#home
你应该使用resources
方法而不是resource
:
resources :users do
resources :lists
end
看看这个Rails 指南文章 http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions它包含带有解释的很好的示例。
为此:
这也是确保用户只能访问他的列表的一个步骤。
您可以使用其中之一devise 的辅助方法 https://github.com/plataformatec/devise#controller-filters-and-helpers: current_user
:
current_user.lists
UPD:但我认为将列表创建为单独的(非嵌套的)资源会更容易。像这样的事情:
# config/routes.rb
Rails.application.routes.draw do
# ...
resources :lists
end
# app/controllers/lists_controller.rb
class ListsController < ApplicationController
before_action :authenticate_user!
def index
@lists = current_user.lists
end
end
所以,在/lists
某些用户只能访问他自己的列表的路径。就是这样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)