about rails route - ruby-on-rails

if i use
namespace :helpcenter do
get "hh/logout"
get 'hh/login'
end
it will match the url helpcenter/hh/logout
my question is how to let these method mapping to the url /hh/logout didn't contains the module name

You can use a scope to achieve this:
scope :module => 'helpcenter' do
resources :articles
end
This will generate a mapping for /articles, /articles/new etc and not helpcenter/articles. It will however still route to the articles controller in the helpcenter namespace. e.g.: app/controllers/helpcenter/articles_controller.rb
Hope that helps.

Related

Rails routing: uninitialized constant ClanController

I have some problems with routing custom controller actions
Routes:
resources :clans do
get 'leave' =>'clan#leave_clan'
get 'dismiss' =>'clan#dismiss_clan'
get 'kick_from_clan/:user_id' =>'clan#kick'
get 'invite/:user_id' =>'clan#invite'
get 'join' =>'clan#join'
end
namespace :admin do
resources :clans
resources :users
end
I know i have clans both in admin namespace and also without but that is how i need it, actions are completely different in them.
And I use a generated route as clan_join_path(clan).
This action results in the next error:
uninitialized constant ClanController
Directory structure:
/app
/controller
/admin
/ClansController.rb
/ClansController.rb
EDIT:
Also invite and kick routes are not generated as expected.
*no path* GET /clans/:clan_id/kick_from_clan/:user_id(.:format) clan#kick
*no path* GET /clans/:clan_id/invite/:user_id(.:format) clan#invite
Any suggestion to the edit part?
You're defining a resource called clans and I presume you have a controller also called ClansController (note the puralization). If you don't have this controller, you'll be wanting to create it.
You probably therefore need to pluralize your routes:
resources :clans do
get 'leave' =>'clans#leave_clan'
get 'dismiss' =>'clans#dismiss_clan'
get 'kick_from_clan/:user_id' =>'clans#kick'
get 'invite/:user_id' =>'clans#invite'
get 'join' =>'clans#join'
end
Also make sure your controller is named clans_controller.rb (pluralized).
You can use member do ... end to properly route based on type of action
resources :clans do
member do
get :leave
get :dismiss
#etc
end
end
This will define the routes as clans/:id/leave clans/:id/dismiss
Check if your clans_controller.rb is intentionally not plural.
resources :clans do
get 'leave' =>'clans#leave_clan'
get 'dismiss' =>'clans#dismiss_clan'
get 'kick_from_clan/:user_id' =>'clans#kick'
get 'invite/:user_id' =>'clans#invite'
get 'join' =>'clans#join'
end
app/controllers/clans_controller.rb
class ClansController < ApplicationController
end

API Versioning for Rails Routes

I'm trying to version my API like Stripe has. Below is given the latest API version is 2.
/api/users returns a 301 to /api/v2/users
/api/v1/users returns a 200 of users index at version 1
/api/v3/users returns a 301 to /api/v2/users
/api/asdf/users returns a 301 to /api/v2/users
So that basically anything that doesn't specify the version links to the latest unless the specified version exists then redirect to it.
This is what I have so far:
scope 'api', :format => :json do
scope 'v:api_version', :api_version => /[12]/ do
resources :users
end
match '/*path', :to => redirect { |params| "/api/v2/#{params[:path]}" }
end
The original form of this answer is wildly different, and can be found here. Just proof that there's more than one way to skin a cat.
I've updated the answer since to use namespaces and to use 301 redirects -- rather than the default of 302. Thanks to pixeltrix and Bo Jeanes for the prompting on those things.
You might want to wear a really strong helmet because this is going to blow your mind.
The Rails 3 routing API is super wicked. To write the routes for your API, as per your requirements above, you need just this:
namespace :api do
namespace :v1 do
resources :users
end
namespace :v2 do
resources :users
end
match 'v:api/*path', :to => redirect("/api/v2/%{path}")
match '*path', :to => redirect("/api/v2/%{path}")
end
If your mind is still intact after this point, let me explain.
First, we call namespace which is super handy for when you want a bunch of routes scoped to a specific path and module that are similarly named. In this case, we want all routes inside the block for our namespace to be scoped to controllers within the Api module and all requests to paths inside this route will be prefixed with api. Requests such as /api/v2/users, ya know?
Inside the namespace, we define two more namespaces (woah!). This time we're defining the "v1" namespace, so all routes for the controllers here will be inside the V1 module inside the Api module: Api::V1. By defining resources :users inside this route, the controller will be located at Api::V1::UsersController. This is version 1, and you get there by making requests like /api/v1/users.
Version 2 is only a tiny bit different. Instead of the controller serving it being at Api::V1::UsersController, it's now at Api::V2::UsersController. You get there by making requests like /api/v2/users.
Next, a match is used. This will match all API routes that go to things like /api/v3/users.
This is the part I had to look up. The :to => option allows you to specify that a specific request should be redirected somewhere else -- I knew that much -- but I didn't know how to get it to redirect to somewhere else and pass in a piece of the original request along with it.
To do this, we call the redirect method and pass it a string with a special-interpolated %{path} parameter. When a request comes in that matches this final match, it will interpolate the path parameter into the location of %{path} inside the string and redirect the user to where they need to go.
Finally, we use another match to route all remaining paths prefixed with /api and redirect them to /api/v2/%{path}. This means requests like /api/users will go to /api/v2/users.
I couldn't figure out how to get /api/asdf/users to match, because how do you determine if that is supposed to be a request to /api/<resource>/<identifier> or /api/<version>/<resource>?
A couple of things to add:
Your redirect match isn't going to work for certain routes - the *api param is greedy and will swallow up everything, e.g. /api/asdf/users/1 will redirect to /api/v2/1. You'd be better off using a regular param like :api. Admittedly it won't match cases like /api/asdf/asdf/users/1 but if you have nested resources in your api it's a better solution.
Ryan WHY U NO LIKE namespace? :-), e.g:
current_api_routes = lambda do
resources :users
end
namespace :api do
scope :module => :v2, &current_api_routes
namespace :v2, &current_api_routes
namespace :v1, &current_api_routes
match ":api/*path", :to => redirect("/api/v2/%{path}")
end
Which has the added benefit of versioned and generic named routes. One additional note - the convention when using :module is to use underscore notation, e.g: api/v1 not 'Api::V1'. At one point the latter didn't work but I believe it was fixed in Rails 3.1.
Also, when you release v3 of your API the routes would be updated like this:
current_api_routes = lambda do
resources :users
end
namespace :api do
scope :module => :v3, &current_api_routes
namespace :v3, &current_api_routes
namespace :v2, &current_api_routes
namespace :v1, &current_api_routes
match ":api/*path", :to => redirect("/api/v3/%{path}")
end
Of course it's likely that your API has different routes between versions in which case you can do this:
current_api_routes = lambda do
# Define latest API
end
namespace :api do
scope :module => :v3, &current_api_routes
namespace :v3, &current_api_routes
namespace :v2 do
# Define API v2 routes
end
namespace :v1 do
# Define API v1 routes
end
match ":api/*path", :to => redirect("/api/v3/%{path}")
end
If at all possible, I would suggest rethinking your urls so that the version isn't in the url, but is put into the accepts header. This stack overflow answer goes into it well:
Best practices for API versioning?
and this link shows exactly how to do that with rails routing:
http://freelancing-gods.com/posts/versioning_your_ap_is
I'm not a big fan of versioning by routes. We built VersionCake to support an easier form of API versioning.
By including the API version number in the filename of each of our respective views (jbuilder, RABL, etc), we keep the versioning unobtrusive and allow for easy degradation to support backwards compatibility (e.g. if v5 of the view doesn't exist, we render v4 of the view).
I'm not sure why you want to redirect to a specific version if a version isn't explicitly requested. Seems like you simply want to define a default version that gets served up if no version is explicitly requested. I also agree with David Bock that keeping versions out of the URL structure is a cleaner way to support versioning.
Shameless plug: Versionist supports these use cases (and more).
https://github.com/bploetz/versionist
Implemented this today and found what I believe to be the 'right way' on RailsCasts - REST API Versioning. So simple. So maintainable. So effective.
Add lib/api_constraints.rb (don't even have to change vnd.example.)
class ApiConstraints
def initialize(options)
#version = options[:version]
#default = options[:default]
end
def matches?(req)
#default || req.headers['Accept'].include?("application/vnd.example.v#{#version}")
end
end
Setup config/routes.rb like so
require 'api_constraints'
Rails.application.routes.draw do
# Squads API
namespace :api do
# ApiConstaints is a lib file to allow default API versions,
# this will help prevent having to change link names from /api/v1/squads to /api/squads, better maintainability
scope module: :v1, constraints: ApiConstraints.new(version:1, default: true) do
resources :squads do
# my stuff was here
end
end
end
resources :squads
root to: 'site#index'
Edit your controller (ie /controllers/api/v1/squads_controller.rb)
module Api
module V1
class SquadsController < BaseController
# my stuff was here
end
end
end
Then you can change all links in your app from /api/v1/squads to /api/squads and you can EASILY implement new api versions without even having to change links
Ryan Bigg answer worked for me.
If you also want to keep query parameters through the redirect, you can do it like this:
match "*path", to: redirect{ |params, request| "/api/v2/#{params[:path]}?#{request.query_string}" }

How to get alternative info from a routing namespace in rails?

Imagine you are working on a f,acebook(to skip the g,f,w) like site, and you need some routes like:
www.mydomain.com/ihome/jim/posts
www.mydomain.com/ihome/jim/post/3
www.mydomain.com/ihome/jim/posts/3/edit.
Then how to set the routes to get the 'jim' part? I know I can use the following if there is no account part:
namespace :ihome do
resources :posts
end
A quick (untested) answer is : use the scope, it will give you a params[:user]
namespace :ihome do
scope ":user" do
resources :posts
end
end
Have a look at the docs here : http://guides.rubyonrails.org/routing.html#defining-defaults

Rails 3 Routing

I have a community_users model that I route in the following way:
resources :communities do
resources :users
end
This creates the route /communities/:id/users/.
I'd like to configure this route so that only the name of the community with the corresponding :id is shown.
In other words, if a community has an id of '1' and the name 'rails-lovers' - the route would read:
/rails-lovers
and not:
/communities/1/users/
You might want to check out the gem friendly_id
That will give you the clean URLs you are looking for.
I'm not quite sure if this is what you're looking for, but:
One option would be to create the route
match ':community_name' => 'users#show_users_for_community'
and then in the UsersController have
def show_users_for_community
#community = Community.find_by_name(params[:community_name])
<do what you need to do here>
end
I'm not sure if that route will match too many URLs or not -- it's a very general route. So if you do this, maybe put it low down in your routes file.

Rails 3 Routing - specifying an exact controller from within a namespace

I'm having a bit of a problem with route namespaces that I've not encountered before. This is actually a part of some gem development I'm doing - but i've reworked the problem to fit with a more generic rails situation.
Basically, I have a namespaced route, but I want it to direct to a generic (top-level) controller.
My controller is PublishController, which handles publishing of many different types of Models - which all conform to the same interface, but can be under different namespaces. My routes look like this:
# config/routes.rb
namespace :manage do
resources :projects do
get 'publish' => 'publish#create'
get 'unpublish' => 'publish#destroy'
end
end
The problem is that this creates the following routes:
manage_project_publish GET /manage/projects/:project_id/publish(.:format) {:controller=>"manage/publish", :action=>"create"}
manage_project_unpublish GET /manage/projects/:project_id/unpublish(.:format) {:controller=>"manage/publish", :action=>"destroy"}
Which is the routes I want, just not mapping to the correct controller. I've tried everything I can think of try and allow for the controller not to carry the namespace, but I'm stumped.
I know that I could do the following:
get 'manage/features/:feature_id/publish' => "publish#create", :as => "manage_project_publish"
which produces:
manage_project_publish GET /manage/projects/:project_id/publish(.:format) {:controller=>"publish", :action=>"create"}
but ideally, I'd prefer to use the nested declaration (for readability) - if it's even possible; which I'm starting to think it isn't.
resource takes an optional hash where you can specify the controller so
resource :projects do
would be written as
resource :projects, :controller=>:publish do
Use scope rather than namespace when you want a scoped route but not a controller within a module of the same name.
If I understand you correct, you want this:
scope :manage do
resources :projects, :only => [] do
get 'publish' => 'publish#create'
get 'unpublish' => 'publish#destroy'
end
end
to poduce these routes:
project_publish GET /projects/:project_id/publish(.:format) {:action=>"create", :controller=>"publish"}
project_unpublish GET /projects/:project_id/unpublish(.:format) {:action=>"destroy", :controller=>"publish"}
Am I understanding your need correctly? If so, this is what Ryan is explaining.
I think what you want is this:
namespace :manage, module: nil do
resources :projects do
get 'publish' => 'publish#create'
get 'unpublish' => 'publish#destroy'
end
end
This does create the named routes as you wish(manage_projects...) but still call the controller ::Publish
It's a bit late but for anyone still struggling with this, you can add a leading slash to the controller name to pull it out of any existing namespace.
concern :lockable do
resource :locks, only: [] do
post "lock" => "/locks#create"
post "unlock" => "/locks#destroy"
end
end
Now if you include that concern anywhere (either namespaced or not) you will always hit the LocksController.

Resources