开发者

How do I set the default format, like JSON, for a customized Devise controller in Rails 3?

My Rails 3 app has three customized controllers for my Devise + OmniAuth integration. I needed to override the standard me开发者_JAVA百科thods, like 'new', for user registrations and sessions. I specifically needed the controller methods to handle redirects and responses that are compatible with JSON formatting.

In my routes.rb file I have the following:

devise_for :users, :controllers => { 
      :omniauth_callbacks => "users/omniauth_callbacks", 
      :registrations      => "users/registrations", 
      :sessions           => "users/sessions"
}

That works as expected. My routes now show the custom controller routes like:

new_user_session GET  /users/sign_in(.:format) {
      :action      =>"new", 
      :controller  =>"users/sessions"
}

new_user_registration GET /users/sign_up(.:format) {
      :action=>"new", 
      :controller=>"users/registrations"
}

To set the default format for a resource I would do something like this:

resources :users, :defaults => { 
      :format => 'json' 
}

So, I tried this:

namespace "users" do
  resources :registrations, :defaults => { 
      :format => 'json' }
  resources :sessions, :defaults => { 
      :format => 'json' }
end

Which did not work as expected. I ended up with these routes:

new_users_registration GET /users/registrations/new(.:format) {
      :format=>"json", 
      :action=>"new", 
      :controller=>"users/registrations"
}

new_users_session GET /users/sessions/new(.:format) {
      :format=>"json", 
      :action=>"new", 
      :controller=>"users/sessions"
}

In order for this to work with my custom overrides in Devise, I need to format 'new_user_registration' not 'new_users_registration'.

I checked the 'devise_for' method and it does not have a :defaults option. I can use the 'devise_scope' method to set the individual routes, but that seems far less concise that the :defaults idiom.

Does anyone know of any routing magic that I can use to make this happen?


I found an answer that isn't necessarily satisfying, but it works. I tried this in routes.rb:

devise_scope :user do
 get "sign_up", :to => "users/registrations#new", 
                :defaults => { :format => 'json' }
end

And I tried this in my custom controllers:

redirect_to new_user_registration_url, :format => 'json'

Neither worked. I am guessing both of those were incorrect in implementation. I finally used this in my custom controllers:

redirect_to :controller => 'users/registrations', 
            :action => 'new', 
            :format => 'json'

That replaced everywhere I originally had:

redirect_to new_user_registration_url

It's more verbose than I like and not very DRY, but it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜