Preserving a custom route on form validation in Rails 3
I'm new to Rails, and I'm building a sample app so I can get my head around both it and the RESTful paradigm.
I have a user signup page, routed to /signup instead of /users/new. If validation on the form fails, it renders 开发者_运维技巧the 'new user' page, but it changes the URL to the create user path, /users.
I'm having difficulty working out how to fix this in a way that's both appropriate for Rails 3 (The solutions I've found appear to be based around Rails 2's routing system) and as RESTful as possible considering I've already overridden /users/new to be something else.
This is supposed to be a learning exercise, after all; I don't care so much about getting it working as understanding how I'm supposed to do things.
Here's routes.rb:
match '/signup', :to => 'users#create', :via => :post #first attempt at solving this
resources :users
match '/signup', :to => 'users#new'
#... routes to other controllers
and this is my controller, handling :create actions:
def create
@user = User.new(params[:user])
if @user.save
flash[:success] = "Welcome to Blather, the hottest new social network until about two weeks from now or TechCrunch gets bored!"
redirect_to @user
else
@title = "Sign Up"
render 'new'
end
end
If you are learning, here are a few pointers:
- check output of
rake routes
to see what routes are being created - see the generated html and what is the url to which the form is posting
You will notice that although you defined routes signup, but RESTful routes still get created and your form posts to "/users" instead of "/signup".
First thing to do is, not generate the routes you do not want, "GET /users/new" and "POST /users", you can do that by changing your routes to:
resources :users, :except => [:new, :create]
get "/signup" => "users#new", :as => :signup # :as option creates a named route for you
post "/signup" => "users#create"
Now when you render the form, you might get some errors regarding some named route not available or you might not. Continue from there and try to solve the problem. Post back with more details if you get stuck again.
精彩评论