Rails new path in nested routes - ruby-on-rails

I've got controller below controller:
module Api
module V1
module Account
class PasswordsController < Devise::PasswordsController
respond_to :json
def create
# some code
end
def update
# some code
end
def is_token_valid
::Account.find_by(reset_password_token: params[:token])
end
end
end
end
end
I want to setup an endpoint for front-end dev where he will check if reset_password_token exist in DB (devise here). I don't know how to made a path like: /api/v1/account/password/is_token_valid
My routes:
namespace :api, defaults: { format: :json } do
namespace :v1 do
namespace :account do
devise_for :accounts, singular: 'account', path: '', controllers: {
sessions: 'api/v1/account/sessions',
registrations: 'api/v1/account/registrations',
confirmations: 'api/v1/account/confirmations',
passwords: 'api/v1/account/passwords',
}
end
resource :account, only: [:show]
EDIT
routes:
root#b2faabb49f91:/usr/src/app# rake routes | grep account
new_account_session GET /api/v1/account/sign_in(.:format) api/v1/account/sessions#new {:format=>:json}
account_session POST /api/v1/account/sign_in(.:format) api/v1/account/sessions#create {:format=>:json}
destroy_account_session DELETE /api/v1/account/sign_out(.:format) api/v1/account/sessions#destroy {:format=>:json}
new_account_password GET /api/v1/account/password/new(.:format) api/v1/account/passwords#new {:format=>:json}
edit_account_password GET /api/v1/account/password/edit(.:format) api/v1/account/passwords#edit {:format=>:json}
account_password PATCH /api/v1/account/password(.:format) api/v1/account/passwords#update {:format=>:json}

Related

Nested Routes Files Rails

I have crafted some nested routes files using the below in my config/initializers:
class ActionDispatch::Routing::Mapper
def draw(routes_name, sub_path=nil)
if sub_path.present?
instance_eval(File.read(Rails.root.join("config/routes/#{sub_path}/#{routes_name}.rb")))
else
instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))
end
end
end
However, when used like this in the routes file:
Rails.application.routes.draw do
scope :api do
["v1"].map { |version| draw :base, "api/" + version }
end
end
The routes there do not appear nested as api/users etc. Not sure why the scope is getting ignored there.
EDIT: More Detailed Example
routes.rb
namespace :api, defaults: { format: :json } do
Rails.application.routes.draw do
["v1"].map { |version| draw :base, "api/" + version }
end
end
base.rb
namespace :v1 do
Rails.application.routes.draw do
[:identity].map { |path| draw path, "api/v1"}
end
end
identity.rb
Rails.application.routes.draw do
# Ensures proper namespace when fetching controllers, but does not add to path for routes
scope module: :identity do
namespace :users do
put '/', action: :update
patch '/', action: :update
get 'user_from_token', action: :update
end
end
end
Rails.application.routes.draw was redundant
# config/routes.rb
Rails.application.routes.draw do
scope :api do
["v1"].map { |version| draw :base, "api/" + version }
end
end
# config/routes/api/v1/base.rb
namespace :v1 do
# Rails.application.routes.draw do
[:identity].map { |path| draw path, "api/v1"}
# end
end
# config/routes/api/v1/identity.rb
# Rails.application.routes.draw do
# Ensures proper namespace when fetching controllers, but does not add to path for routes
scope module: :identity do
namespace :users do
put '/', action: :update
patch '/', action: :update
get 'user_from_token', action: :update
end
end
# end
$ rake routes
Prefix Verb URI Pattern Controller#Action
v1_users PUT /api/v1/users(.:format) v1/identity/users#update
PATCH /api/v1/users(.:format) v1/identity/users#update
v1_users_user_from_token GET /api/v1/users/user_from_token(.:format) v1/identity/users#update
rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update
rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create

Case insensitive routes in Rails

How can I have a portion of a route Capitalized? For example I have a route scim/v2/user but I'd like it to be scim/v2/User (User capitalized). How can I achieve this while still using resource.
Routes file:
namespace :scim, defaults: { format: :json } do
namespace :v2 do
resource :user, only: [:create, :update, :show]
end
end
When I run $rake routes, I get this:
scim_v2_user POST /scim/v2/user(.:format) scim/v2/users#create {:format=>:json}
GET /scim/v2/user(.:format) scim/v2/users#show {:format=>:json}
PATCH /scim/v2/user(.:format) scim/v2/users#update {:format=>:json}
PUT /scim/v2/user(.:format) scim/v2/users#update {:format=>:json}
I'd like to either have the routes be /scim/v2/User or have them remain the same but have a way of mapping /scim/v2/User to /scim/v2/user.
By default resource wants a direct mapping between the resource name and the controller, but you can simplify use an upper case resource name and manually specify the controller to get around this:
namespace :scim, defaults: { format: :json } do
namespace :v2 do
resource :User, :controller => 'users', only: [:create, :update, :show]
end
end
Generates
Prefix Verb URI Pattern Controller#Action
scim_v2_User GET /scim/v2/User(.:format) scim/v2/users#show {:format=>:json}
PATCH /scim/v2/User(.:format) scim/v2/users#update {:format=>:json}
PUT /scim/v2/User(.:format) scim/v2/users#update {:format=>:json}
POST /scim/v2/User(.:format) scim/v2/users#create {:format=>:json}
I was able to solve this by manually specifying the path and controller. I specified that path should be Users (capitalized). Below is code in my routes file:
namespace :scim, defaults: { format: :json } do
namespace :v2 do
resources :user,
path: "Users",
controller: "users",
only: [:create, :update, :index, :show]
end
end

jsonapi-resources; wrong self link

I configured json-resouce-api.
But the self link generated by json-resource-api is wrong.
The code seems to checks the module hierarchy of the resource class and completely ignores how rails generates the routes.
routes.rb
require 'api_constraints'
Rails.application.routes.draw do
namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/' do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
# resources :subscriptions, only: [:index, :new, :create]
# jsonapi_resources :subscriptions, only: [:index, :new, :create]
jsonapi_resources :subscriptions
end
end
resouces/api/V1/subscription_recource.rb
class Api::V1::SubscriptionResource < JSONAPI::Resource
attributes :id, :third-service_id, :created_at, :updated_at
model_name 'Subscription'
# def custom_links(options)
# {self: nil}
# end
end
What I got => http://api.localhost.local:3000/api/v1/subscriptions/1
but it should be http://api.localhost.local:3000/subscriptions/1
How can I fix this?
UPDATE
rake routes
[DUPLICATE ATTRIBUTE] `id` has already been defined in SubscriptionResource.
Prefix Verb URI Pattern Controller#Action
api_v1_subscriptions GET /subscriptions(.:format) api/v1/subscriptions#index {:format=>:json, :subdomain=>"api"}
POST /subscriptions(.:format) api/v1/subscriptions#create {:format=>:json, :subdomain=>"api"}
api_v1_subscription GET /subscriptions/:id(.:format) api/v1/subscriptions#show {:format=>:json, :subdomain=>"api"}
PATCH /subscriptions/:id(.:format) api/v1/subscriptions#update {:format=>:json, :subdomain=>"api"}
PUT /subscriptions/:id(.:format) api/v1/subscriptions#update {:format=>:json, :subdomain=>"api"}
DELETE /subscriptions/:id(.:format) api/v1/subscriptions#destroy {:format=>:json, :subdomain=>"api"}
stripe_event /stripe-events StripeEvent::Engine
UPDATE2
This issue is totally the same as github.com/cerebris/jsonapi-resources/issues/591
Monkey Pack can be applied, but it's little bit risky.
For now ( 2016, Oct 5th ), I couldn't find any other ways than
namespace :api do
namespace :v1 do
jsonapi_resources :subscriptions
end
end
You can try it:
namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: "" do
namespace :v1, path: "" do
jsonapi_resources :subscriptions
end
end

uninitialized constant SessionsController in API

I'm writing an API and am trying to login with the API and am getting uninitialized constant SessionsController error followed by the tip to "Try running rake routes for more information on available routes." when I try to go to the URL
http://localhost:3000/api/v1/login as a POST
My routes show that the route and action exist as shown:
api_v1_users GET /api/v1/users(.:format) api/v1/users#index {:format=>"json"}
POST /api/v1/users(.:format) api/v1/users#create {:format=>"json"}
new_api_v1_user GET /api/v1/users/new(.:format) api/v1/users#new {:format=>"json"}
edit_api_v1_user GET /api/v1/users/:id/edit(.:format) api/v1/users#edit {:format=>"json"}
api_v1_user GET /api/v1/users/:id(.:format) api/v1/users#show {:format=>"json"}
PUT /api/v1/users/:id(.:format) api/v1/users#update {:format=>"json"}
DELETE /api/v1/users/:id(.:format) api/v1/users#destroy {:format=>"json"}
new_api_v1_user_session GET /api/v1/login(.:format) sessions#new {:format=>"json"}
api_v1_user_session POST /api/v1/login(.:format) sessions#create {:format=>"json"}
destroy_api_v1_user_session DELETE /api/v1/logout(.:format) sessions#destroy {:format=>"json"}
api_v1_user_omniauth_authorize GET|POST /auth/:provider(.:format) authentications#passthru {:provider=>/twitter|facebook/, :format=>"json"}
api_v1_user_omniauth_callback GET|POST /auth/:action/callback(.:format) authentications#(?-mix:twitter|facebook) {:format=>"json"}
api_v1_user_password POST /api/v1/password(.:format) api/v1/passwords#create {:format=>"json"}
new_api_v1_user_password GET /api/v1/password/new(.:format) api/v1/passwords#new {:format=>"json"}
edit_api_v1_user_password GET /api/v1/password/edit(.:format) api/v1/passwords#edit {:format=>"json"}
PUT /api/v1/password(.:format) api/v1/passwords#update {:format=>"json"}
cancel_api_v1_user_registration GET /api/v1/cancel(.:format) registrations#cancel {:format=>"json"}
api_v1_user_registration POST /api/v1(.:format) registrations#create {:format=>"json"}
new_api_v1_user_registration GET /api/v1/sign_up(.:format) registrations#new {:format=>"json"}
edit_api_v1_user_registration GET /api/v1/edit(.:format) registrations#edit {:format=>"json"}
PUT /api/v1(.:format) registrations#update {:format=>"json"}
DELETE /api/v1(.:format) registrations#destroy {:format=>"json"}
When I try to access the account using the authentication_token url parameter, it works fine.
http://localhost:3000/api/v1/users/39?user_token=DxwspVzYSpsiLosd9xcE
Using that I can make PUT and GET requests no problem.
My routes look like this:
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :users
devise_for :users, :path => '', path_names: {sign_in: "login", sign_out: "logout"},
controllers: {omniauth_callbacks: "authentications", registrations: "registrations", sessions: "sessions"}
end
end
I assume it's a problem in my SessionsController, but can't figure out why the PUT request would work, but the POST wouldn't. Here is the SessionsController:
module Api
module V1
class SessionsController < Devise::SessionsController
before_filter :authenticate_user!, except: [:create, :destroy]
before_filter :ensure_params_exist
skip_before_filter :verify_authenticity_token
def create
resource = User.find_for_database_authentication(email: params[:user_login][:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:user_login][:password])
sign_in("user", resource)
resource.ensure_authentication_token!
render 'api/v1/sessions/new.json.jbuilder', status: 201
return
end
invalid_login_attempt
end
def destroy
current_user.reset_authentication_token
render json: {success: true}
end
protected
def ensure_params_exist
return unless params[:user_login].blank?
render json: {success: false, message: "missing user_login parameter"}, status: 422
end
def invalid_login_attempt
render 'api/v1/sessions/invalid.json.jbuilder', status: 401
end
end
end
end
So in my routes file I had
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :users
devise_for :users, path: '', path_names: {sign_in: "login", sign_out: "logout"},
controllers: {omniauth_callbacks: "authentications", registrations: "registrations", sessions: "sessions"}
end
end
I removed sessions: "sessions" and everything works great. I'm not going to mark this as the correct answer because I don't know why this fixed the problem, or more specifically, why adding sessions: "sessions" was causing the error in the first place. Hopefully someone can explain this for future readers.
EDIT:
I realized much later that the problem was that I was referencing the sessions_controller, when I wanted to reference the api/v1/sessoins_controller There is no regular sessions_controller I just use the Devise one, but there is a sessions_controller in the API/V1 namespace. So that is why the problem was happening.
For future reference for anyone else who comes across this problem, the error is telling you the controller you're looking for doesn't exist as it should, so to troubleshoot, make sure you are looking for the controller in the correct place, and with the correct name.
In a similar case for an API app with rails 6 and devise 4.8.1 I used scope and devise_scopeto configure routes according to devises doc. devise_for was skip-ed.
In my case:
scope :api, defaults: { format: :json } do
scope :v1 do
devise_for :users, skip: :all
devise_scope :user do
post '/sign_in', to: 'devise/sessions#create'
delete '/sign_out', to: 'devise/sessions#destroy'
post '/sign_up', to: 'devise/registrations#create'
put '/account_update', to: 'devise/registrations#update'
delete '/account_delete', to: 'devise/registrations#destroy'
end
end
end

Rails 3: respond_with errors on undefined URL helper

I have an Artwork model that is manipulated only by API endpoints right now. (You'll see why this is important shortly). Those API endpoints are declared like so in my routes.rb file:
namespace :api do
namespace :v1, :defaults => { :format => :json } do
resources :artworks, :only => [:create, :destroy, :index, :show, :update]
This results in the following routes:
api_v1_artworks GET /api/v1/artworks(.:format) api/v1/artworks#index {:format=>:json}
POST /api/v1/artworks(.:format) api/v1/artworks#create {:format=>:json}
api_v1_artwork GET /api/v1/artworks/:id(.:format) api/v1/artworks#show {:format=>:json}
PUT /api/v1/artworks/:id(.:format) api/v1/artworks#update {:format=>:json}
DELETE /api/v1/artworks/:id(.:format) api/v1/artworks#destroy {:format=>:json}
Relevant code:
class Api::V1::ArtworksController < Api::V1::ApiController
def create
artwork = Artwork.create(artwork_params)
respond_with artwork
end
The Problem
When #create succeeds, respond_with chokes:
`undefined method `artwork_url' for #<Api::V1::ArtworksController:0x007fea1b4c67f8>`
It's expecting the helper for the HTTP Location to be artwork_url. How do I tell it to use api_v1_artwork_url instead? Can I alias the URL helper?
In this case, you'd need to specify the namespace for the responder. Try:
respond_with :api, :v1, artwork

Resources