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

时间:2013-06-27 17:30:03

标签: ruby-on-rails devise routes

  1. 我应该何时在devise_for区块中嵌套路线?请举一个或两个示例来显示用例。 (路线#1)

  2. 如果:foo_object:users相关联,:user has_one :foo_object,我是否需要在:foo_object下嵌套:users? (路线#2):users是设计:users模型。

  3. 路线#1:

    devise_for :users  
    resource :foo_object
    

    路线#2:

    devise_for :users
    resources :users do      
      resource :foo_object
    end
    

1 个答案:

答案 0 :(得分:25)

以下示例:

devise_for :users, :path => 'accounts'

resources :users do
    resources :orders
end

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

devise_for :users do 
   resources: somereosouce
end 

所有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"}

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

devise_for :users 

resource :users do 
   resource :foo_object
end 

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

class Users < ActiveRecord::Base
  has_many :foo_object
end

class FooObject < ActiveRecord::Base
  belongs_to :users
end

然后您的嵌套资源将是

   resource :users do 
     resource :foo_object 
   end

希望这可以解决问题。您也可以阅读Nested Resource with Devise - Rails3