Rails3 + Devise:何时在devise_for和嵌套资源中嵌套资源

HM1*_*HM1 11 routes ruby-on-rails devise

  1. 我什么时候应该在devise_for街区筑巢?请举一个或两个示例来显示用例.(路线#1)

  2. 如果:foo_object相关联:users,从而:userHAS_ONE :foo_object,我需要巢:foo_object之下:users?(路线#2):users是设计:users模型.

路线#1:

devise_for :users  
resource :foo_object
Run Code Online (Sandbox Code Playgroud)

路线#2:

devise_for :users
resources :users do      
  resource :foo_object
end
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 25

以下示例:

devise_for :users, :path => 'accounts'

resources :users do
    resources :orders
end
Run Code Online (Sandbox Code Playgroud)

以上意味着认证路径将是"/accounts/sign_in","/accounts_sign_up"等等.有些人可能不知道重要的是承认它实际上devise_for :users没有映射到UsersController和模型.它甚至不是一条资源路线,尽管它看起来很像.这就是为什么我们不能像下面那样对待它:

devise_for :users do 
   resources: somereosouce
end 
Run Code Online (Sandbox Code Playgroud)

一切devise_for都是映射以下路线:

# Session routes for Authenticatable (default)
     new_user_session GET  /users/sign_in                    {:controller=>"devise/sessions", :action=>"new"}
         user_session POST /users/sign_in                    {:controller=>"devise/sessions", :action=>"create"}
 destroy_user_session GET  /users/sign_out                   {:controller=>"devise/sessions", :action=>"destroy"}

# Password routes for Recoverable, if User model has :recoverable configured
    new_user_password GET  /users/password/new(.:format)     {:controller=>"devise/passwords", :action=>"new"}
   edit_user_password GET  /users/password/edit(.:format)    {:controller=>"devise/passwords", :action=>"edit"}
        user_password PUT  /users/password(.:format)         {:controller=>"devise/passwords", :action=>"update"}
                      POST /users/password(.:format)         {:controller=>"devise/passwords", :action=>"create"}

# Confirmation routes for Confirmable, if User model has :confirmable configured
new_user_confirmation GET  /users/confirmation/new(.:format) {:controller=>"devise/confirmations", :action=>"new"}
    user_confirmation GET  /users/confirmation(.:format)     {:controller=>"devise/confirmations", :action=>"show"}
                      POST /users/confirmation(.:format)     {:controller=>"devise/confirmations", :action=>"create"}
Run Code Online (Sandbox Code Playgroud)

所以说你可以做以下事情,但会有一些冲突:

devise_for :users 

resource :users do 
   resource :foo_object
end 
Run Code Online (Sandbox Code Playgroud)

关于嵌套资源的一点点,如果您有类似以下内容:

class Users < ActiveRecord::Base
  has_many :foo_object
end

class FooObject < ActiveRecord::Base
  belongs_to :users
end
Run Code Online (Sandbox Code Playgroud)

那么你的嵌套资源就是

   resource :users do 
     resource :foo_object 
   end
Run Code Online (Sandbox Code Playgroud)

希望这可以解决问题.此外,您可能希望阅读带有Devise - Rails3嵌套资源

  • 感谢您澄清'devise_for`问题.我读过的最佳解释! (2认同)