Rails routing and controller modules -namespacing? - ruby-on-rails

I have trouble creating a module for my controller, and getting my routes to point to that module within the controller.
Getting this error:
Routing Error
uninitialized constant Api::Fb
So, this is how my routes are set up:
namespace :api do
namespace :fb do
post :login
resources :my_lists do
resources :my_wishes
end
end
end
In my fb_controller i want to include modules that will give me paths like this:
/api/fb/my_lists
This is some of my fb_controller:
class Api::FbController < ApplicationController
skip_before_filter :authenticate_user!, :only => [:login]
include MyLists # <-- This is where i want to include the /my_lists
# namespace(currently not working, and gives me error
# mentioned above)
def login
#loads of logic
end
end
The MyLists.rb file(where i define a module) is in the same directory as the fb_controller.rb.
How can i get the namespacing to point to my module inside of the fb_controller, like /api/fb/my_lists ?

The namespace you have set up is looking for a controller class that looks like this
class Api::Fb::MyListsController
If you want to have a route that looks like /api/fb/my_lists but you want to still use the FbController instead of having a MyListsController you need to set up your routes to look like this
namespace :api do
scope "/fb" do
resources :my_lists, :controller => 'fb'
end
end
In my opinion, instead of including a module MyLists in your FbController seems kind of awkward.
What I would probably do is have a module FB with a generic FbController then have MyListsController < FbController. Anyway, this is beyond the scope of your question.
The above should answer for your needs.
EDIT
From your comments, and my assumptions on what you're trying to do this is a small example:
config/routes.rb
namespace :api do
scope "/fb" do
post "login" => "fb#login"
# some fb controller specific routes
resources :my_lists
end
end
api/fb/fb_controller.rb
class Api::FbController < ApiController
# some facebook specific logic like authorization and such.
def login
end
end
api/fb/my_lists_controller.rb
class Api::MyListsController < Api::FbController
def create
# Here the controller should gather the parameters and call the model's create
end
end
Now, if all you want to create a MyList Object then you could just do the logic directly to the model. If, on the other hand, you want to handle some more logic you'd want to put that logic in a Service Object that handles the creation of a MyList and its associated Wishes or your MyList model. I would probably go for the Service Object though. Do note, the service object should be a class and not a module.

In your example, Fb isn't a namespace, it's a controller. The namespace call is forcing your app to look for a Fb module that doesn't exist. Try setting up your routes like this:
namespace :api do
resource :fb do
post :login
resources :my_lists do
resources :my_wishes
end
end
end
You can optionally define a new base controller for the API namespace:
# app/controllers/api/base_controller.rb
class Api::BaseController < ApplicationController
end
If you do so, your other controllers can inherit from this:
# app/controllers/api/fb_controller.rb
class Api::FbController < Api::BaseController
end
Running rake routes should give you an idea of how your other controllers are laid out. Just a warning - it's generally not recommended to have resources nested more than 1 deep (you're going to end up with complex paths like edit_api_fb_my_list_my_wish_path). If you can architect this in a simpler way, you'll probably have an easier time of this.

Related

Rails 5 - How to Have Controllers inside Subfolder?

I have a subfolder api in my controllers folder.
So when I call POST "/api/auth" I would like the program to get there using rails conventions.
I.E. I don't want to write the route for each call, but to use rails "patent" that makes rails go to CRUD actions understanding the PUT, POST, GET by itself.
So in my routes.rb I have:
namespace :api do
resources :debts, :auth
end
But when I POST (or GET) with localhost:3000/api/auth I get:
ActionController::RoutingError (uninitialized constant Api::AuthController)
What am I missing?
Please note that I also need to have many controllers inside the subfolder. Is there a short match for all?
You have to put your controller in a sub folder too en then do e.g.
# /app/controllers/api/debts_controller.rb
module Api
class DebtsController < ApiController
end
end
# /app/controllers/api/auth_controller.rb
module Api
class AuthController < ApiController
end
end
Then in base controller folder:
# /app/controllers/api_controller.rb
class ApiController < ApplicationController
end
You need to namespace the class also in order to get this working.
The following 2 ways can be used:
module Api
class AuthController < ApplicationController
# Your controller code here
end
end
class Api::AuthController < ApplicationController
# Your controller code here
end
If you have some code that needs to be run for every controller inside the Api namespace, you can make an Api base controller, but it's not necessary.

Rails Routing Design Question for Scoped Resources

What would be the preferred routing and namespace controller scheme for a scoped resource in Rails. ie. for index of projects that are scheduled:
1) /scheduled/projects
2) /projects/scheduled
3) /projects?scheduled=true
Option 1 is kind of what our existing codebase does, every new feature that access the resource differently get its own namespace. But it seems like option 2 is a possibility as well.
Looking for opinion from folks working on sufficiently large Rails codebase with a large number of controllers.
Option 1: scope is the namespace
scheduled/projects=> scheduled/projects#index
namespace :scheduled do
resources :projects
end
resources :projects
/projects/3
bin/rails g controller projects
class ProjectsController < ApplicationController
def show
render plain: "show projects/#{params[:id]}"
end
end
/scheduled/projects
bin/rails g controller scheduled/projects
class Scheduled::ProjectsController < ApplicationController
def index
render plain: 'index scheduled/projects'
end
end
Pros:
All the scheduled items are group under one folder, kind of similar to the the admin route scoping example in https://guides.rubyonrails.org/v5.2/routing.html.
Cons:
The various scoped ProjectsController are scattered in different places.
Option 2 - scope specified after the resource
projects/scheduled => projects/scheduled#index
namespace :projects do
resources :scheduled
end
# config/routes.rb
resources :projects
/projects/3
bin/rails g controller projects
class ProjectsController < ApplicationController
def show
render plain: "show projects/#{params[:id]}"
end
end
/projects/scheduled
bin/rails g controller projects/scheduled
class Projects::ScheduledController < ApplicationController
def index
render plain: 'index projects/scheduled'
end
end
Namespace scheme is similar to the Inboxes::PendingController example in.http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/
Inboxes is the resource like projects
Pending is the state like scheduled
Pros: Everything Projects related would be under the same namespace, could make it easier to share things like filtering logic
Cons: projects/scheduled index route could look similar to projects/:id show route with scheduled as the :id
Option 3 - scope is the query params
/projects?scheduled=true => projects/scheduled#index
Using advance constraint to map query params to routes.
Pros: all the projects related routes are simply /projects
Cons: maybe not all filters are applicable to a certain scoped resource. ie. /projects?scheduled=true&filter[status]=false may not make sense.

Rails routing with namespaces and nested routes

I have an email_template model that has a nested resource moves to handle moving an email_template from one folder to another.
However, I want to namespace these actions in a :templates namespace because I have several other resources that are template items as well.
Since I'm namespacing, I don't want to see templates/email_templates/:id in the URL, I'd prefer to see templates/emails/:id.
In order to accomplish that I have the following:
# routes.rb
namespace :templates do
resources :emails do
scope module: :emails do
resources :moves, only: [:new, :create]
end
end
end
Everything works fine when I do CRUD actions on the emails, since they are just using the :id parameter. However, when I use the nested moves, the parent ID for the emails keeps coming across as :email_id and not :email_template_id. I'm sure this is the expected behavior from Rails, but I'm trying to figure out how the parent ID is determined. Does it come from the singular of the resource name in the routes, or is it being built from the model somehow?
I guess it's ok to use templates/emails/:email_id/moves/new, but in a perfect world I'd prefer templates/emails/:email_template_id/moves/new just so developers are clear that it's an email_template resource, not a email.
# app/controllers/templates/emails_controller.rb
module Templates
class EmailsController < ApplicationController
def show
#email_template = EmailTemplate.find(params[:id])
end
end
end
# app/controllers/templates/emails/moves_controller.rb
module Templates
module Emails
class MovesController < ApplicationController
def new
# Would prefer to reference via :email_template_id parameter
#email_template = EmailTemplate.find(params[:email_id])
end
def create
#email_template = EmailTemplate.find(params[:email_id])
# Not using strong_params here to demo code
if #email_template.update_attribute(:email_tempate_folder_id, params[:email_template][:email_template_folder_id])
redirect_to some_path
else
# errors...
end
end
end
end
end
You could customize the parameter as:
resources :emails, param: :email_template_id do
...
end

How to follow DRY principles in different namespaces Rails 4.2?

Basically I've developed an app which has two namespaces: admin, api and the public one (simply resources :users for instance). All works fine, however I'm repeating myself quite a bit as some of the controllers in api for instance could easily be used in admin.
How can I DRY my code in this case keeping the namespaces?
Thanks!
There are a couple ways I can think of doing it:
(NOT RECOMMENDED) - Send the urls to the same controller in your routes.rb file.
Shared namespace that your controllers inherit from
For example you could have:
# controllers/shared/users_controller.rb
class Shared::UsersController < ApplicationController
def index
#users = User.all
end
end
# controllers/api/users_controller.rb
class Api::UsersController < Shared::UsersController
end
# controllers/admin/users_controller.rb
class Admin::UsersController < Shared::UsersController
end
The above would allow you to share your index action across the relevant controllers. Your routes file in this case would look like this:
# config/routes.rb
namespace :api do
resources :users
end
namespace :admin do
resources :users
end
That's definitely a lot of code to share one action, but the value multiplies as the number of shared actions does, and, most importantly, your code is located in one spot.

Rails 4.1: Creating routes by calling method in controller

I want to create a method that, when called from a controller, will add a nested resource route with a given name that routes to a specific controller. For instance, this...
class Api::V1::FooController < ApplicationController
has_users_route
end
...should be equivalent to...
namespace :api do
namespace :v1 do
resources :foo do
resources :users, controller: 'api_security'
end
end
end
...which would allow them to browse to /api/v1/foo/:foo_id/users and would send requests to the ApiSecurityController. Or would it go to Api::V1::ApiSecurityController? It frankly doesn't matter since they're all in the same namespace. I want to do it this way because I want to avoid having dozens of lines of this:
resources :foo do
resources :users, controller: 'api_security'
end
resources :bar do
resources :users, controller: 'api_security'
end
Using a method is easier to setup and maintain.
I'm fine as far as knowing what to do once the request gets to the controller, but it's the automatic creation of routes that I'm a little unsure of. What's the best way of handling this? The closest I've been able to find is a lot of discussion about engines but that doesn't feel appropriate because this isn't separate functionality that I want to add to my app, it's just dynamic routes that add on to existing resources.
Advice is appreciated!
I ended up building on the blog post suggested by #juanpastas, http://codeconnoisseur.org/ramblings/creating-dynamic-routes-at-runtime-in-rails-4, and tailoring it to my needs. Calling a method from the controllers ended up being a bad way to handle it. I wrote about the whole thing in my blog at http://blog.subvertallmedia.com/2014/10/08/dynamically-adding-nested-resource-routes-in-rails/ but the TL;DR:
# First draft, "just-make-it-work" code
# app/controllers/concerns/user_authorization.rb
module UserAuthorization
extend ActiveSupport::Concern
module ClassMethods
def register_new_resource(controller_name)
AppName::Application.routes.draw do
puts "Adding #{controller_name}"
namespace :api do
namespace :v1 do
resources controller_name.to_sym do
resources :users, controller: 'user_security', param: :given_id
end
end
end
end
end
end
end
# application_controller.rb
include UserAuthorization
# in routes.rb
['resource1', 'resource2', 'resource3'].each { |resource| ApplicationController.register_new_resource(resource) }
# app/controllers/api/v1/user_security_controller.rb
class Api::V1::UserSecurityController < ApplicationController
before_action :authenticate_user!
before_action :target_id
def index
end
def show
end
private
attr_reader :root_resource
def target_id
# to get around `params[:mystery_resource_id_name]`
#target_id ||= get_target_id
end
def get_target_id
#root_resource = request.fullpath.split('/')[3].singularize
params["#{root_resource}_id".to_sym]
end
def target_model
#target_model ||= root_resource.capitalize.constantize
end
def given_id
params[:given_id]
end
end

Resources