I have the following code
application.rb
config.autoload_paths += %W(#{config.root}/config/routes)
routes.rb
Rails.application.routes.draw do
root to: 'summary#index'
extend General
end
/config/routes/general.rb
module General
def self.extended(router)
router.instance_exec do
# devise routes
devise_for :users, controllers: { sessions: 'users/sessions' }
end
end
end
I get uninitialized constant General when loading the app.
I''m using Ruby 2.2.6 and Rails 5.0.2
in rails 6, you can use draw(:general), which will look for route definition in config/routes/general.rb
You can emulate this with an initializer:
module RoutesSubfolder
# Extension to Rails routes mapper to provide the ability to draw routes
# present in a subfolder
#
# Another solution would be to add the files to `config.paths['config/routes']`
# but this solution guarantees the routes order
#
# Example: <config/routes.rb>
#
# Rails.application.routes.draw do
# # this will eval the file config/routes/api.rb
# draw :api
#
# Example:
# draw :'api/whatever' # loads config/routes/api/whatever.rb
#
def draw(name)
path = Rails.root.join('config', 'routes', "#{name}.rb")
unless File.exist?(path)
raise StandardError, "Unable to draw routes from non-existing file #{path}"
end
instance_eval(File.read(path), path.to_s, 1)
end
end
ActionDispatch::Routing::Mapper.prepend(RoutesSubfolder)
The only difference with what you proposed is that:
you don't need to change the autoload_path
in general.rb, you directly declare your routes the same way you'd do in config/routes.rb inside the Rails.application.routes.draw do block
Related
To limit devise auto generated routes, I have this in my route file...
## config/routes.rb
# Restrict auto generated devise routes
devise_scope :user do
resource :users,
only: [:new, :create, :edit, :update],
controller: 'users/registrations',
path_names: { new: 'sign_up' },
as: :user_registration
end
Controller:
## app/controllers/users/registrations_controller
module Users
# Copied by `devise` generator so we could override things.
class RegistrationsController < Devise::RegistrationsController
def new
# some logic
end
def create
# some logic
end
# # Overriding and call to `super` for these two method removes unused routes warning, I don't want this
# # rubocop:disable Lint/UselessMethodDefinition
# def edit
# super
# end
# def update
# super
# end
# # rubocop:enable Lint/UselessMethodDefinition
rails_best_practices linter is giving warning restrict auto-generated routes users (only: [:new, :create]) if I don't override the edit & update methods in RegistrationsController.
Is there a way to disable RestrictAutoGeneratedRoutesCheck for those routes?
Or what would be the most feasible way to resolve this warning? Thank you.
What about a custom rails_best_practices.yml with a tweaked RestrictAutoGeneratedRoutesCheck entry? See: https://github.com/flyerhzm/rails_best_practices
Go to rails_best_practices.yml and you can apply the ignored_files option on any rule by giving a regexp or array of regexp describing the path of the files you don't want to be:
In your case RestrictAutoGeneratedRoutesCheck{ignored_files: 'routes.rb'}.
I'm having issues trying to add a static subdomain while also running apartment gem..
Essentially I want to do something like:
constraints subdomain: 'docs' do
get 'some/page'
end
however when I place this code in my routes file and attempt to go to docs.mysite.co I get the following error:
Apartment::TenantNotFound at /
One of the following schema(s) is invalid: "docs" "public", "shared_extensions"
my entire routes file is as follows:
class SubdomainPresent
def self.matches?(request)
request.subdomain.present?
end
end
class SubdomainBlank
def self.matches?(request)
request.subdomain.blank?
end
end
Rails.application.routes.draw do
constraints subdomain: 'docs' do
get 'some/page'
end
constraints(SubdomainPresent) do
mount ImageUploader::UploadEndpoint => "/images/upload"
root 'account_dashboard#index'
devise_for :users
devise_scope :user do
get 'login', to: 'devise/sessions#new'
end
resources :accounts
end
constraints(SubdomainBlank) do
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'
root 'visitor#index'
resources :accounts, only: [:new, :create]
end
end
Any assistance here would be greatly appreciated!Please let me know if I need to add further info!
EDIT # 1 Adds Application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module PatrolVault20161116Web
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.active_job.queue_adapter = :sidekiq
end
end
This error is caused when apartment gem cannot find a schema to run a subdomain. First, you should create a schema by creating a tenant by your subdomain name in ruby console.
Apartment::Tenant.create "docs"
After creating docs tenant in console your subdomain will be working nicely.
I follow the ruby on rails tutorial guide but I keep having the error as stated in my title. I have totally no idea why does it appear.
routes.rb
Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root ‘application#hello’
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def hello
render text: “Hello”
end
end
Please advise me on this because I have been trying around and even reinstalling everything again based on the Ruby on Rails tutorial.
The problem is in this line root ‘application#hello’.
It looks like your system uses wrong symbol for single quotation mark (the one you are using is 8216 unicode character and you should be using the 39 one). Also in your controller render text: “Hello” would throw an error.
The lines should be root 'application#hello' and render text: "Hello"
This may be changed in your system keyboard settings. Cannot be more accurate since I don't know what system are you using but the issue is definitely in wrong symbols for single\double quotations.
I would like to use a controller with EC module like EC::HomeController.
# app/cotrollers/ec/home_controller.rb
class EC::HomeController < ApplicationController
def index
end
end
It works in rails console.
[1] pry(main)> EC::HomeController
=> EC::HomeController
But in routes.rb it doesn't work...
# config/routes.rb
Rails.application.routes.draw do
namespace :ec do
namespace :home do
get "/" => :index
end
end
end
And access to http://localhost:3000/ec/home, then get
LoadError in Ec::HomeController#index
Unable to autoload constant Ec::HomeController, expected
/Users/wadako/coincheck/app/controllers/ec/home_controller.rb to define it
It loads Ec::HomeController not EC::HomeController.
Can't I use capital module name for rails4 routes?
in config/initializers create inflections.rb. In this file define:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'EC'
end
This will allow you to use your module name in caps.
Lets work on that routes.rb!
Rails.application.routes.draw do
resources :home, only: :index, module: 'EC'
end
This should give you a route helper home_path that maps to EC:HomeController#index
I have a Rails app that has only consisted of backend code so far (a little custom workflow engine, Redis, foreman, etc). Today I tried to add the first controller to the application, but I can't get the new controller to load.
I used:
rails generate controller CollectedData new --no-test-framework
And got back:
create app/controllers/collected_data_controller.rb
route get "collected_data/new"
invoke erb
create app/views/collected_data
create app/views/collected_data/new.html.erb
invoke helper
create app/helpers/collected_data_helper.rb
invoke assets
invoke coffee
create app/assets/javascripts/collected_data.js.coffee
invoke scss
create app/assets/stylesheets/collected_data.css.scss
And I also ran rake routes and got this:
collected_data_new GET /collected_data/new(.:format) collected_data#new
But whenever I load http://localhost:3000/collected_data/new in my browser, I get:
Not Found: /collected_data/new
Here is the content of my routes.rb file:
Crows::Application.routes.draw do
get "collected_data/new"
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
Procfile contents:
redis: redis-server config/redis/redis.conf
clock: bundle exec rake resque:scheduler --trace
cp_resp_poller: bundle exec rake environment resque:work QUEUE=cp_resp_poller
cp_req_sender: bundle exec rake environment resque:work QUEUE=cp_req_sender --trace
server: rails server
I have also tried restarting WEBrick.
Update: I noticed that Webrick is returning HTTP 404 when requesting this controller (or any new controller that I've tried to add, for that matter).
FIXED: Please see my own answer to this question.
FIXED: I fixed this by changing my config.ru file.
The original contents were:
require ::File.expand_path('../config/environment', __FILE__)
run Crows::Application
require 'resque/server'
run Rack::URLMap.new "/resque" => Resque::Server.new
I fixed the controller not found issue by commenting out the last two lines above related to Resque. Those last two lines were added early on while developing the workflow/backend part of my application and enable a web-based admin interface for Resque.
Update: I now have my Rails app (plus its web controllers, etc) and the Resque web admin interface running side-by-side. I got this working by removing those last two lines from the config.ru file and adding the following lines to my routes.rb file:
resources :resque_web_admin
mount Resque::Server, :at => "/resque"