让我们看看我是否能很好地解释自己的疑虑。
我有一个由 Devise 管理的用户模型。所以在我的 route ,我有:
devise_for :users
在 用户 模型,我与模型有关联 计划 .协会是:
User has_many Plans
Plan belongs_to User
此时,我还拥有计划模型的资源,因此我可以获取所有计划、显示特定计划等。但我想更进一步。
我希望能够查看特定用户的计划并让特定用户查看他自己的计划并对其进行编辑。
因此,例如,每当我去:
/users/:id/计划
我希望能够查看该特定 :id 用户的计划。如果访问该 url 的用户是登录的用户,我希望他能够编辑这些计划。
我该如何管理所有这些行为?有什么 gem 可以帮助它吗?或者我需要在 View 中做条件语句,如果 current_user ...
最佳答案
这与使用任何其他嵌套资源没有什么不同。调用 devise_for
在 routes.rb
文件不提供到用户模型的 RESTful 路由。考虑一下没有嵌套资源的情况,只需一个标准的设计安装。如果您要 rake routes
您会得到类似于以下内容的信息:
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
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
sign_in GET /sign_in(.:format) devise/sessions#new
这不提供索引或显示用户的任何内容,因此您仍然需要为此添加路由:
resources :users, only: [:index, :show]
现在你得到:
users GET /users(.:format) users#index
user GET /users/:id(.:format) users#show
好的,现在我们到达了某个地方,然后它只是添加了嵌套资源,而 Devise 一直不关心它。
resources :users, only: [:index, :show] do
resources :plans
end
这为您提供了所需的资源丰富的路由
user_plans GET /users/:user_id/plans(.:format) plans#index
POST /users/:user_id/plans(.:format) plans#create
new_user_plan GET /users/:user_id/plans/new(.:format) plans#new
edit_user_plan GET /users/:user_id/plans/:id/edit(.:format) plans#edit
user_plan GET /users/:user_id/plans/:id(.:format) plans#show
PUT /users/:user_id/plans/:id(.:format) plans#update
DELETE /users/:user_id/plans/:id(.:format) plans#destroy
这就是它的全部内容。在这个问题上,设计不受你的影响。
关于ruby-on-rails - 对 Rails 中的嵌套资源和身份验证感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14090894/