Custom Ruby Routes in Model
Ok, these two related questions are specific to Railscast # 21 :
I have problems with routes. Two questions:
1) The routes in the tutorial seem to refer to the root of the application; I want them to be relative to the model root. So
" http://example.com/login
" I need to be " http://example.com/model/login
" (and vice versa to exit).
I am using permalinks to link to my posts and I donβt know how to specify an override because every time I try to use " http://example.com/model/login
" I get an error that says it cannot find the write "login". How can I override this for login / logout?
2) Going to a custom route for me doesn't seem to store the custom route in my address bar. So going to " http://example.com/login
" will take me to the correct page, but the browser now says " http://example.com/session/new
" in the address bar. This does not happen in the tutorial: the app serves the correct page and stores the custom route in the address bar. How can I make this happen for me?
## Sessions Controller
class SessionController < ApplicationController
def create
session[:password] = params[:password]
flash[:notice] = "Successfully Logged In"
redirect_to :controller => 'brokers', :action => 'index'
end
def destroy
reset_session
flash[:notice] = "Successfully Logged Out"
redirect_to login_path
end
end
## Routes
ActionController::Routing::Routes.draw do |map|
map.resources :brokers, :session
map.login 'login', :controller => 'session', :action => 'create'
map.logout 'logout', :controller => 'session', :action => 'destroy'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
source to share
What does "model root" mean? You have to create routes to controllers and their actions. The controller must interact with the model.
The error messages can be a little confusing, but as far as I can see this url:
http://example.com/model/login
will call an action named login in a controller named model with an empty id (which probably doesn't exist) using this route:
map.connect ':controller/:action/:id'
If you want to have a "subfolder" in your route, you can use namespaces, I don't remember every detail about this, but you can find a lot of information about it here . A word of warning: namespaces make it much easier to debug a route, I was really interested in figuring out which route is actually being used. I ended up creating many very specific routes to make sure the correct one was used.
source to share