Subdomains in routes.rb - ruby-on-rails

as I am trying to create web with subodmain for every user i coded as below:
In below controller i am checking if subdomain from sign_in devise page belons to user in User.rb table. If not i am logging out.
class ApplicationController < ActionController::Base
before_action :authenticate_user!
before_action :check_domain
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:slug])
devise_parameter_sanitizer.permit(:account_update, keys: [:slug])
end
def check_domain
unless current_user.nil?
#domain = User.find_by(email: current_user.email)
if #domain.slug != request.subdomain
sign_out_and_redirect(current_user)
flash.alert = "User not found."
end
end
end
end
At this moment I have routes.rb as below:
Rails.application.routes.draw do
resources :devise
resources :places
resources :people_items
resources :people, only: [:edit, :update]
resources :gift_items
resources :gifts, only: [:edit, :update]
resources :program_items
resources :story_items
devise_for :users
root to: 'pages#index'
get '/home', to: 'output#home'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :pages do
member do
delete :delete_file
end
end
resources :stories, only: [:edit, :update]
resources :programs, only: [:edit, :update]
resources :galleries, only: [:edit, :update] do
member do
delete :delete_image
end
end
get 'informations/information'
resources :aboutus, only: [:edit, :update]
end
I modified one more settings in config/environments/development.rb
config.action_dispatch.tld_length = 1
Everything is working fine.
In tutorials i found out that for working subdomains properly I should modify routes.rb as below. But what is the purpose of modification file below? Do I really need to touch routes.rb? That's my question.
constraints subdomain: /.*/ do
resources :pages
end
Do I really need to modify this? Or what is purpose of this modification? Is that really necessary?
Thank you so much for your advices!

Constraints in routes.rb allow you to restrict when routes should or shouldn't be matched, returning a 404 in the event that they do not.
You can do this on a per-route basis for params like so:
get 'products/:category', to: "products#index", category: /(fruit|electronics|medicine)/, as: :products
This would allow requests to http://yourdomain.com/products/fruit but not to http://yourdomain.com/products/vehicles for example. Accessing any forbidden domains would provide you with a 404 response.
You can provide generic constraints to a bunch of different routes by enclosing them in a constraints block, like so:
constraints ->(req) { Site.exists?(subdomain: req.subdomain) } do
resources :articles, path: "blog", only: [:index, :show]
...
end
So here, we're checking that a Site record exists with the subdomain provided. If not, we return a 404.

Related

Rails redirect all nested routes

Is there a way that I can redirect all the child routes to root_url or to some other routes depending on the type of authorization? Here are my routes
resources :invitations, only: [:edit, :update, :destroy]
namespace :app do
resources :projects, only: [:index, :show, :create] do
resources :changelogs, only: [:index]
resources :team_members, only: [:index]
end
end
The app namespaced routes, that is the routes starting with /app/projects/:id should be redirect to either root_url or to invitations_url depending on the type of authorization.
If you are using devise and have a user table with a column admin:boolean, you can check for admin in routes.rb like this:
authenticated :user, lambda {|u| u.admin? } do
namespace :app do
#your routes
end
end
This would make "your nested routes" completely unavailable for unauthenticated user and users that are not admin.
If you want redirects, you can add something like this in routes.rb:
get '/stories', to: redirect('/articles')
Otherwise you can simply do redirects in the controllers like projects_controller.rb:
before_action :authenticate_admin, only: [:show, :edit]
def authenticate_admin
unless current_user.admin? redirect_to root_path, alert: "You are not authorized"
end

rails - how to target nested controller for nested resource route

In my routes.rb I have
namespace :admin do
resources :clients do, only: [:index] do
resources :products, only: [:index, :new, :create]
end
resources :products, only: [:index]
end
Notice that I have two lines for resources :products. One is nested within resources :clients and the other as a top-level resource on :admin; each of these two has a different purpose in the application.
rake routes gives me:
admin_clients GET /admin/clients(.:format) admin/clients#index
admin_client_products GET /admin/clients/:client_id/products(.:format) admin/products#index
POST /admin/clients/:client_id/products(.:format) admin/products#create
new_admin_client_product GET /admin/clients/:client_id/products/new(.:format) admin/products#new
admin_products GET /admin/products(.:format) admin/products#index
I have a admin_client_products for the nested product#index resource. I also have admin_products for the top-level product#index resource. However, they point to the same controller action: admin/product#index.
Question: At this point, I need rails to deduce that these are two different actions. Using rails conventions, is there a way to tell rails that these two resources should have different controller actions i.e. one that should hit admin/products#index and the other should hit admin/clients/products#index?
The nested route should hit this:
class Admin::Clients::ProductsController < Admin::BaseController
def index; end
end
The top-level route should hit this:
class Admin::ProductsController < Admin::BaseController
def index; end
end
Definitely you can!
Here you need to customize your resourceful route by explicitly specifying a controller to use for the resource. The :controller option will let you do that.
So, in your case, specifying the controller as clients/products for the admin_clients_products resource would work in your desired way.
namespace :admin do
resources :clients, only: [:index] do
resources :products, only: [:index, :new, :create], controller: 'clients/products'
end # ------------------------------
resources :products, only: [:index]
end
rails routes will now give you what you want:
admin_client_products GET /admin/clients/:client_id/products(.:format) admin/clients/products#index
POST /admin/clients/:client_id/products(.:format) admin/clients/products#create
new_admin_client_product GET /admin/clients/:client_id/products/new(.:format) admin/clients/products#new
admin_clients GET /admin/clients(.:format) admin/clients#index
admin_products GET /admin/products(.:format) admin/products#index
=========================
Extra bits:
If you want to omit the /admin portion from the url (I mean, if your application's routing design permits to), then you could use: scope module: 'admin' do...end like the following:
scope module: 'admin' do
resources :clients, only: [:index] do
resources :products, only: [:index, :new, :create], controller: 'clients/products'
end
resources :products, only: [:index]
end
and suddenly your routes will start looking awesome :)
client_products GET /clients/:client_id/products(.:format) admin/clients/products#index
POST /clients/:client_id/products(.:format) admin/clients/products#create
new_client_product GET /clients/:client_id/products/new(.:format) admin/clients/products#new
clients GET /clients(.:format) admin/clients#index
products GET /products(.:format) admin/products#index

Rails error Couldn't find Blog with 'id'=new

I have a weird error when I want to redirect users to the root_url when they try to access blogs/new url in my app.
My routes are
resources :blogs, only: [:index, :show] do
resources :comments, only: [:create]
end
namespace :admin do
resources :blogs
resources :users, only: [:index, :show]
resources :comments, only: [:create, :new, :destroy]
end
My non-admin blogs controller looks like this:
class BlogsController < ApplicationController
before_action :set_blog, only: [:show]
def show
unless #blog
redirect_to blogs_path
flash[:notice] = "You are not authorized to create a post."
end
end
def index
#blogs = Blog.all
end
private
def set_blog
#blog = Blog.find(params[:id])
end
end
I get the error Couldn't find Blog with 'id'=new.
In rails, the priority of routes goes from top to bottom. Meaning, when you try to hit /blogs/new, the route gets matched with the show action of blogs defined in the top of your routes.rb.
blogs/new gets matched with /blogs/:id which is mapped to blogs#show action.
In the set_blog method, params[:id] is new and since there is no record with the id of new, you're getting that weird error.
How to get around this? Change the priority of your routes.
Move the following block below the admin namespaced routes.
namespace :admin do
resources :blogs
resources :users, only: [:index, :show]
resources :comments, only: [:create, :new, :destroy]
end
resources :blogs, only: [:index, :show] do
resources :comments, only: [:create]
end
By the way, your question says that you want to avoid non-admin users to access blogs#new. If that's the case, you should try to hit /admin/blogs/new and not /blogs/new.
If you had done that, you wouldn't have gotten the error in the first place. But still, its good to know about the priority of routes in rails.
Hope this helps!

No route matches when trying to sign up

I'm having troubles with routes in Ruby on Rails. I've configured routes this way
resources :users do
collection do
resource :registrations, only: [:show, :create]
resource :sessions, only: [:new, :create, :destroy]
resource :confirmations, only: [:show]
end
end
And I have a RegistrationsController where I have two endpoints (new, create)
class RegistrationsController < ApplicationController
skip_before_filter :authenticate!
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
flash[:notice] = t("registrations.user.success")
redirect_to :root
end
end
end
But when I do rails s and I put localhost:3000/users/registrations/create or new I get a "no route matches". And I think the route exist because If I do raake routes I get this
registrations POST /users/registrations(.:format) registrations#create
GET /users/registrations(.:format) registrations#show
I know it should be a silly mistake but I don't get it. I appreciate any help
When you define routes for registrations, you're limiting it to just [:show, :create]:
resource :registrations, only: [:show, :create]
But your controller (correctly!) is presuming that there are two routes: new (to show the registration form) and create (to create the new user). You need to change your routes so that they match your controller actions:
resources :users do
collection do
resource :registrations, only: [:new, :create] # Updated this line!
resource :sessions, only: [:new, :create, :destroy]
resource :confirmations, only: [:show]
end
end

skip before_action in controller when routes are nested in rails

I have routes like this. I have nested batches routes with streams.
resources :batches
resources :streams do
resources :batches do
collection do
post 'create_batch'
end
end
end
When i go to the link.
create_batch_stream_batches_path(stream)
In bacthesControlller.rb it calls for before action :set_batch which it should not as the before_action
before_action :set_batch, only: [:show, :edit, :update, :destroy]
def create_batch
logger.info params
binding.pry
end
I tried with skip_before_action for create_batch but it didn't work.
In your nested route, you can simply pass a custom parameter, which will be passed on to the controller during a request:
resources :batches
resources :streams do
resources :batches, skip: true do
end
end
end
In the controller you check whether the parameter is passed, and don't run the hook if the flag is set:
before_action :set_batch, unless: -> { params[:skip] }

Resources