开发者

Rails 3 renaming routes

I am just getting started with Rails 3 and I do not quite understand how to go about renaming routes.

What I want:

To rename the path to the users#show controller/action pair. So instead of the URL being www.example.com/users/show/1 it would just be www.example.com/1/home

In the future, I'd also like to be able to add additional paths onto the end such as:

www.example.com/1/home/profile/

How my user resources are set up:

resources :users, :except => [:destroy] do
  resources :favorites, :only => [:show, :update]
  resources :profiles, :only => [:show, :update]
end

What I tried:

match :home, :to => 'users#show' 

What happened:

ActiveRecord::RecordNotFound in UsersController#show

  Couldn't find User without an ID

What's in the development.log file:

Started GET "/home" for 127.0.0.1 at 2011-03-10 13:36:15 -0500
  Processing by UsersController#show as HTML
  [1m[35mUser Load (1.6ms)[0m  SELECT "users".* FROM "users" WHERE ("users"."id" = 101) LIMIT 1
Completed   in 192ms

ActiveRecord::RecordNotFound (Couldn't find User without an ID):
  app/controllers/users_controller.rb:19:in `show'

What's in the user controller:

def show
  @user = User.find(params[:id])

  respond_to do |format|
    format.html # show.html.haml
  end
end

So, apparently it开发者_高级运维 is storing the user id, as shown in the development log as 101 but for whatever reason I am still getting this error?

Any help you can provide is greatly appreciated!


You should provide a segment key in your match:

match ':id/home' => 'users#show'

But with this renaming you will get not RESTful routes.

Another thing is with user profiles. If one user can have only one profile it's better to declare singular resource routes:

resources :users do
  resource :profile
end


I can't explain why it's making that SQL request, but it's not using 101 to look up the user. If it were, you would get this error:

ActiveRecord::RecordNotFound: Couldn't find User with ID=101

Since it says Coundln't find User without and ID, then it's probably calling User.find(nil)

Anyway, we're doing something similar in our application, except with names instead of IDs. They are matched at the bottom of the routes file, like so:

match '/:current_region' => 'offers#show', :as => 'region_home'

and then in your controller, you can load the model from the parameter params[:current_region]:

def load_region
    @current_region = Region.find_by_slug(params[:current_region] || cookies[:current_region])
end

We use it as a filter before a lot of actions, so we define it like so rather than explicitly call it in the show action:

class OffersController < ActionController::Base
    before_filter :load_region

    def show
        # do stuff with @current_region here
    end
end

You'll just have to change :current_region to :id

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜