six7zero9 six7zero9 - 7 months ago 46
Ruby Question

Devise Ajax 404 routing error

I am testing ajax with devise and am running into this error in console:

GET https://example.com/users/get_company?foo=bar 404 (Not Found)


and rails server is returning:

ActionController::RoutingError (uninitialized constant UsersController):


A little bit of code:

config/routes.rb

devise_for :users, :controllers => {registrations: 'registrations'}
devise_scope :user do
authenticated :user do
root 'account#show', as: :authenticated_root
end

unauthenticated do
root 'devise/sessions#new', as: :unauthenticated_root
end
end

get 'users/get_company', as: 'get_company'


initializers/devise.rb

config.http_authenticatable_on_xhr = true
config.navigational_formats = ['*/*', :html]


controllers/registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
respond_to :json
def get_company
@company = Company.first.name
respond_to do |format|
format.js
end
end
end


In views/devise/registrations there is new.html.erb, get_company.js.coffee and in assets/javascripts there is get_company.js.coffee.
These seem to be working fine because the event happens and then I am getting the routing error.

Any help would be greatly appreciated as I am just learning this to help out with a project. Please ask for any additional code or anything that might help explain the situation better.

Answer

Hey your route of get_company is missing /, so it would be:

devise_for :users, :controllers => {registrations: 'registrations'}
devise_scope :user do
  authenticated :user do
    root 'account#show', as: :authenticated_root
  end

  unauthenticated do
    root 'devise/sessions#new', as: :unauthenticated_root
  end
  # 1: If you put your get_company route here, it still works
  get '/users/get_company' => 'registrations#get_company', as: 'get_company'
end    

# 2: If you put your get_company route here, it works as well
# get '/users/get_company' => 'registrations#get_company', as: 'get_company'

You code will work fine either you put the route in position #1 or #2