使用自定义路径渲染操作

时间:2010-02-05 20:48:16

标签: ruby-on-rails

我试图在用户注册验证失败时保持一个漂亮的URL

我有一个类似于以下内容的路由文件:

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

这很有效,但如果用户在注册期间输入了无效信息,则create方法会执行以下操作:

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

这样可行,但如果信息正确,则会将URL切换到domain.com/users。如果我将它切换到redirect_to'/ signup'它可以工作,但输入的所有先前信息都会丢失,我最好还是保留它。

在验证失败期间,有没有办法保留我的网址?

2 个答案:

答案 0 :(得分:2)

您需要为路线添加条件:

# 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 }

然后,您需要确保您的控制器和视图正确处理它们:

# 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 %>

答案 1 :(得分:0)

尝试添加路线:

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

以你的形式:

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