gpt4 book ai didi

ruby-on-rails - 设计中的嵌套资源

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:44 26 4
gpt4 key购买 nike

我是 Rails 的新手,我需要一些关于我的路线和正确路由逻辑的建议。我正在开发一个非常简单的应用程序,用户可以在其中发布列表。用户(设计模型)有很多列表,列表属于一个用户。我的 list 表中有一个 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

我怎样才能让我的路线实现这一目标:

/users/:user_id/lists(.:format)

这也是确保用户只能访问他的列表的一个步骤。

最佳答案

您应该使用resources 方法而不是resource:

resources :users do
resources :lists
end

看看这个Rails Guides article它包含很好的例子和解释。

为此:

It would also be a stepping point to make sure that the user has access only to his lists.

您可以使用 devise's helper methods 之一:当前用户:

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 路径中,一些用户将只能访问他自己的列表。就是这样。

关于ruby-on-rails - 设计中的嵌套资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27712947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com