Rails scaffold built table called assets - now route errors - ruby-on-rails

I used scaffold to build a table called "assets". The files were created. The "rake db:create" worked fine. I added " resources :assets" to my routes.rb file. I now get route errors. I ran "rake routes" and none of the routes for "assets" show up.
Is it bad to use a table name "assets"?
Or is something else wrong?

The asset pipeline uses /assets by default.
You can either change the default assets path by using this in application.rb:
config.assets.prefix = '/something-else'
Or change the routing for your assets resource by using:
resources :assets, :path => 'something-else'
edit: Actually the second option is probably the better choice because I forgot that asset_path is available by default and belongs to the asset pipeline. If you changed your default assets prefix and used asset_path #asset hoping to generate a link to assets#show then it might cause problems.
Use the :as option in your routes to change the path/url methods it generates.
resources :assets, :path => 'things', :as => 'things'
things_path results in /things and routes to the index action of the assets controller
thing_path #asset results in /things/:id and routes to the show action of the assets controller
etc.

Related

Route override doubles records

I'd like to override a default path of an Spree/Rails extension.
The extension spree_contact_us defines default route in it's config/routes.rb this way:
Spree::Core::Engine.routes.draw do
resources :contacts,
:controller => 'contact_us/contacts',
:only => [:new, :create]
match 'contact-us' => 'contact_us/contacts#new', :as => :contact_us
end
In the routes table there is just one record for route named contact-us:
contact_us /contact-us(.:format) spree/contact_us/contacts#new
If I pass following override in main application's config/routes.rb to routes.prepend method
Spree::Core::Engine.routes.prepend do
match 'napiste-nam' => 'contact_us/contacts#new', :as => :contact_us
end
rake routes displays routes to a new named path twice, when passed to routes.append even three times:
contact_us /napiste-nam(.:format) spree/contact_us/contacts#new
contact_us /napiste-nam(.:format) spree/contact_us/contacts#new
Can anybody explain this behaviour ?
The problem here is that you will be creating an ambiguous named route :contact_us which when referenced by contact_us_path will return the path for the last entry in routes because you are redefining it.
The duplication does seem strange but I have not looked at how spree handles these things.
In order to avoid this you could rename the secondary route such as
Spree::Core::Engine.routes.append do
match 'napiste-nam' => 'contact_us/contacts#new', :as => :contact_us_czech
end
This should create 2 routes in which you could use contact_us_path and contact_us_czech_path which will both lead to the same place. then create a method to determine which to use.
Or just add the new route directly into the spree routing tables as (PROBABLY NOT VALID DUE TO CALL TO routes_reloader in Spree Core.
match 'napiste-nam' => 'contact_us/contacts#new', :as => :contact_us
match 'contact_us' => 'contact_us/contacts#new', :as => :contact_us
Just remember that this means that contact_us_path with always reference the second route.
Edit
It seems Spree builds the default routes and then reloads them after initializing as is stated in the code
# We need to reload the routes here due to how Spree sets them up.
# The different facets of Spree (backend, frontend, etc.) append/prepend
# routes to Core *after* Core has been loaded.
#
# So we wait until after initialization is complete to do one final reload.
# This then makes the appended/prepended routes available to the application.
config.after_initialize do
Rails.application.routes_reloader.reload!
end
I believe this is causing the named route :contact_us to be routed to it's defined route meaning that you defined it as contact_us and then redefined it as napiste-nam and since a variable can have only 1 value it held on to the second one on reload!. Due to this fact I am not sure you can do this directly through Spree.
Using
Spree::Core::Engine.routes.draw
instead of
Spree::Core::Engine.routes.prepend
solved the routes duplication problem for me.

rails namespaced route with root only works in development

namespace :admin do
root :to => "admin#index"
end
I can visit localhost:3000/admin and it works.
When I deploy to heroku myapp.herokuapp.com/admin does not. It produced this
ActionController::RoutingError (uninitialized constant Admin::AdminController):
My controller is actually AdminController, not Admin::AdminController and I'm not quite sure what the difference is or how to fix this.
Again, it all works locally.
You can see in rake routes output that for this namespaced route rails uses :controller => 'admin/admin'. When it comes to finding controller class it converts admin/admin into Admin::AdminController. So controllers for namespaced routes are usually placed under app/controllers/namespace_name directory and wrapped in NamespaceName module. In your case it should be Admin::AdminController class defined in app/controllers/admin/admin_controller.rb.
Though, it's really interesting why your configuration works fine in development but breaks in production mode (I tried and successfully reproduced it). I believe it has smth to do with loading and caching classes in production mode, because setting config.cache_classes = true in config/environments/development.rb cause it breaking in development mode as well.
And as zoltarSpeaks noted it's supposed to be root :to => "admin#index" instead of root :to => "Admin#index".
Another thing to note is that namespaces for routes are usually used when there are multiple related controllers. If all you need is single AdminController you can config your routes like that:
resources :admin, :only => :index
In that case no other changes are needed (if you want to have other default actions besides index just remove :only option).
I'm away from my laptop so can't check but is:
root :to => "Admin#index"
supposed to be:
root :to => "admin#index"
instead? It might not make any difference.
Do you have an Admin folder within controllers with an Admin controller inside it then?
If you could show us your controller code too it would be helpful thanks.

Splitting Routes File Into Multiple Files

I'm working w/ a Rails 3 application and I want to split up the routes into separate files depending on the subdomain. Right now I have this in my routes.rb file:
Skateparks::Application.routes.draw do
constraints(:subdomain => 'api') do
load 'routes/api.rb'
end
end
And In my routes/api.rb file I have:
resources :skateparks
This doesn't seem to work though because if I run rake routes I get
undefined method `resources' for main:Object
Also, if I try to navigate to http://0.0.0.0:3000/ I get:
Routing Error
No route matches "/"
In Rails 3.2, config.paths is now a hash, so #sunkencity's solution can be modified to:
# config/application.rb
config.paths["config/routes"] << File.join(Rails.root, "config/routes/fooroutes.rb")
Sunkencity's answer seems to be identical to the following link, but for completeness' sake: https://rails-bestpractices.com/posts/2011/05/04/split-route-namespaces-into-different-files/
Note that routes defined later will override routes defined earlier. However, if you use something like
config.paths.config.routes.concat(
Dir[Rails.root.join('config/routes/*.rb')])
you don't know in what order the files will be read. So use
config.paths.config.routes.concat(
Dir[Rails.root.join('config/routes/*.rb')].sort)
instead, so you at least know they will be in alphabetical order.
Add the route file to the app route loading path:
# config/application.rb
config.paths.config.routes << File.join(Rails.root, "config/routes/fooroutes.rb")
Wrap your other route file in a block like this.
#config/routes/fooroutes.rb
Rails.application.routes.draw do |map|
match 'FOO' => 'foo/bar'
end
Works for me in rails 3.0
We used this in our app:
config.paths['config/routes'] = Dir["config/routes/*.rb"]
If you try to access config.paths['config/routes'] normally, it returns the relative path to config/routes.rb, so by doing the above you're giving it relative paths to all of the files in your routes folder and removing the reference to config/routes.rb

Overriding named routes provided by Rails 3 Engines

I am working on a Ruby on Rails 3(.0) application that uses a Rails engine. However, in my local application, I want to override one of the routes provided by the Rails engine.
From the engine config/routes.rb:
match 'their_named_route' => 'controller#action', :as => 'the_route'
From my application config/routes.rb:
match 'my_named_route' => 'controller#action', :as => 'the_route'
However, when I inspect the routes, both seem to be active (and their route appears to "win", at least within the engine controllers)
$ rake routes
the_route /my_named_route(.:format) {:controller=>"controller", :action=>"action"}
the_route /their_named_route(.:format) {:controller=>"controller", :action=>"action"}
Is there a good way to force my local application's named route to take priority?
I got around this by moving my engine's routes from config/routes.rb to a class method in the engine class itself:
module MyEngine
class Engine < Rails::Engine
def self.routes
MyRailsApp::Application.routes.draw do
resources :products
end
end
end
end
and then in the base app's routes file:
MyRailsApp::Application.routes.draw do
# Routes for base app including the ones overriding MyEngine::Engine.
MyEngine::Engine.routes
end
I can then happily override any routes in the base app with those in the engine.
Note that the overriding routes need to be defined before the overridden routes since the earlier defined routes take precedence over later ones.
I'm afraid that there's no such easy way. The routes are defined in lib/action_dispatch/routing/mapper.rb:271, which calls add_route on the RouteSet (defined in rack-mount-0.6.14/lib/rack/mount/route_set.rb, and on line 71 the name is attached). There's no remove_route method, and the Engine's route is added last. You can add your route manually after the application is initialized with Rails.application.routes.draw instead of having it in routes.rb, or you can patch the Engine.
There is no way to override a route within an engine. Instead, you must define an overruling route. You can do this by calling prepend on the engine's router:
An::Engine.routes.prepend do
root :to => "somewhere#action"
end
If the engine's namespace is isolated, this will use the SomewhereController from inside the engine's namespace. If not, it will use the typical SomewhereController.
If you want to override a route to return a 404, the best way I can think of is to redirect to a 404 page:
match "/route_goes_here" => redirect("/404")
You need add initializer hook to config/application.rb, like this:
class Application < Rails::Application
config.encoding = "utf-8"
...
initializer :add_routing_paths do |app|
their_routes_path = app.routes_reloader.paths.select{|path| path =~ /DIR/}.first
app.routes_reloader.paths.delete(their_routes_path)
app.routes_reloader.paths.unshift(their_routes_path)
end
end
It's load roues.rb of you engine first and you can override their routes.
You can prepend routes as suggest by Ryan Bigg above. I found that in order overrule the named route helper with my custom route I need to call append instead of prepend, like so:
An::Engine.routes.append do
root :to => "somewhere#action"
end
Otherwise the app contains both routes and the named helper for engine's router is the last definition, and therefore the one that is applied.
Routing rules defined in routes.rb are applied from the top down until a match is found. I was able to override the route defined in the mounted engine simply by moving the higher-priority rule above the line where the engine is mounted. So,
get 'about', controller: 'static', action: 'about', as: 'about'
mount My::Engine => '/'
results in the app routing /about/ requests to (in this case) the static controller, whereas:
mount My::Engine => '/'
get 'about', controller: 'static', action: 'about', as: 'about'
results in the app routing /about/ requests to the route defined in the mounted engine.
To Replace the default routes path provided by gem or engine we can achive that in following way.
For me I wanted to replace 'spree_user' with 'account' etc from all routes
/user/spree_user/sign_in I did this in following way
Step 1
Create config/some_engine_route_override.rb
Copy the content of engine route file and update the routes as per need
Step 2
in application.rb use the folllowing hook
# Override Spree Core routes in order to translate products routes
initializer "delete_spree_core_routes", after: "add_routing_paths" do |app|
new_spree_auth_route_path = File.expand_path('../../config/some_engine_route_override.rb', __FILE__)
routes_paths = app.routes_reloader.paths
spree_devise_auth_route_path = routes_paths.select{ |path| path.include?("spree_auth_devise") }.first
if spree_devise_auth_route_path.present?
spree_core_route_path_index = routes_paths.index(spree_devise_auth_route_path)
routes_paths.delete_at(spree_core_route_path_index)
routes_paths.insert(spree_core_route_path_index, new_spree_auth_route_path)
end
end

How to remove controller name in REST design in Rails3?

Given a User resource, it goes like this
/user/:shortname
But how can the controller name be removed to get just
/:shortname
How can I declare this in routes.rb while keeping all CRUD functionality instant?
Updated: After reading this I'm moving to Sinatra over Rails to handle this API-like design better.
Define a custom match:
match ':shortname' => 'users#action'
Replace action in users#action with the name of the action that is supposed to receive the request. Just remember to place it in the appropriate order in your routes file. Rails looks at each line of your routes file starting at the top and selects the first matching route. ':shortname' would match any first-level path, including /users! So put it below any routes using a first-level path, which would include all of your resource routes. Here's an example:
resources :users
resources :posts
match '/blog' => 'posts#index'
match ':shortname' => 'users#action'
In routes, you should be able to do something like
resource :users, :path => '/:shortname'
Try that out and rake routes to see if that comes out as expected.

Resources