开发者

Rendering Actions with Custom Routes

I am trying to maintain a pretty URL when having a user register with failed validation

I have a routes file that looks like the following:

map.resources :users
map.signup '/signup', :controller => "users", :action => "new"

This works well enough, except that if a user enters invalid information during registration then the create method does the following:

def create
    @user = User.new(params[:user])
    if @user.save
       flash[:notice] = "Successfully Registered."
       redirect_to root_url
    else
       render :action => 'new'
    end
end

This works, but if the information is correct it switches the URL to domain.com/users. If I switch it to redirect_to '/signup' it works, but all the previous inform开发者_如何学编程ation that was entered is lost, and I would ideally like to maintain that.

Is there any way to keep my nice urls during a failed validation?


You'll need to add conditions to your routes:

# Routes files
map.resources :users

map.signup "/signup", :controller => "users", :action => "new", :conditions => { :method => :get }
map.signup "/signup", :controller => "users", :action => "create", :conditions => { :method => :post }

Then, you'll need to make sure your controller and view handle them correctly:

# Controller
def new
  @user = User.new
end

def create
  @user = User.new(params[:user])

  if @user.save
    flash[:notice] = "Successfully registered."
    redirect_to root_url
  else
    render "new"
  end
end

# new.html.erb
<% form_for @user, :url => signup_path do |form| %>
   ....
<% end %>


Try adding to routes:

map.signup_post '/signup', :controller => "users", :action => "create", :method => :post

And in your form:

<%= form_for @user, :url => signup_post_path do |f| %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜