Rails redirect_to REST
I'm in the process of learning RoR, and I'm liking everything that I'm discovering so far. I'm switching over from the PHP-based CodeIgniter framework, and I have a problem in using the redirect_to method.
I've defined a basic Users model which I use to handle registration - data gets stored fine in the DB, but the problem is when redirecting after signing up a user to the system.
Basically, the profile page is of the following format: /users/:name/:id
I have a routes file defined as such:
resources :users
match '/users/:name/:id', :to => 'users#show'
And here is my create method
def create
@title = "User creation"
@user = User.new(params[:user])
if @user.save
info = { :name => @user.name, :id => @user.id }
redirect_to info.merge(:action => "show")
else
@title = 'Sign Up'
render 'new'
end
end
However this will generate an url of the following format:
http://localhost:3000/users/27?name=Testing
When I'm actually looking for something like this:
http://localhost:3000/users/Testing/27
It just makes sense for me from a SEO point of view that a profile page URL look like that. I've been searching the inter-webs, but I only find solutions to different problems. I hope someone can help.
SOLVED Both versions that were suggested by Ryan worked fine, and I decided to stick to the second one, since it feels more RESTful. I'll just share the config I have right now - mind you, the User model may not be all that correct, but it's the to_param function that's important. Also, I've noticed that it doesn't work if I make the function private - that makes sense, but I just thought that I'd share that for someone that may be running into that sort of problem.
Here's my routes file:
resources :users
And here is my Users model:
class User < ActiveRecord::Base
attr_accessible :name, :email
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name,
:presence => true,
:length => { :within => 5..50 }
validates :email,
:presence => true,
:format => { :with => email_regex},
:uniqueness => { :case_sensitive => false }
def to_param
"#{id}-#{name.parameterize}"
end
end
And here's my controller create开发者_开发技巧 function:
def create
@title = "User creation"
@user = User.new(params[:user])
if @user.save
redirect_to @user
else
@title = 'Sign Up'
render 'new'
end
end
Define your route like this:
get '/users/:name/:id', :to => 'users#show', :as => "user"
Then redirect to it using this helper:
redirect_to(user_path(@user.name, @user.id))
Alternatively, you could just stick with resources :users
and not have to define your own route. The difference here is that your route would be something like /users/1-testing
rather than users/1/testing
, but the advantage is that you would be more Rails standard.
To do this, define a to_param
method in your model, like this:
def to_param
"#{id}-#{name.parameterize}
end
Then Rails will use the output of the to_param
method in your routes.
精彩评论