0

如何从控制器正确渲染名为 route 的导轨?

路线.rb:

get "logout" => "sessions#destroy", :as => "logout"
get "login" => "sessions#new", :as => "login"
get "signup" => "users#new", :as => "signup"

root :to => "home#index"

resources :users
resources :sessions
resources :likes

用户控制器.rb:

def new
  @user = User.new
end

def create
  @user = User.new params[:user]
  if @user.save
    login(params[:user][:email], params[:user][:password])
    redirect_to root_url, :notice => "Welcome! You have signed up successfully."
  else
    render :new
  end
end

问题是:注册页面打开/signup,当数据@user没有正确填写render :new并被调用时,而不是去/signup它去的 url /users。我会使用redirect_to但 id 不喜欢,因为我希望将错误保存在页面上以告诉用户哪些数据未提供。

添加后更新match "signup" => "users#create", :via => "post"

root             /                            {:controller=>"home", :action=>"index"}
users     GET    /users(.:format)             {:action=>"index", :controller=>"users"}
          POST   /users(.:format)             {:action=>"create", :controller=>"users"}
edit_user GET    /users/:id/edit(.:format)    {:action=>"edit", :controller=>"users"}
user      GET    /users/:id(.:format)         {:action=>"show", :controller=>"users"}
          PUT    /users/:id(.:format)         {:action=>"update", :controller=>"users"}
          DELETE /users/:id(.:format)         {:action=>"destroy", :controller=>"users"}
signup    GET    /signup(.:format)            {:action=>"new", :controller=>"users"}
          POST   /signup(.:format)            {:action=>"create", :controller=>"users"}

谢谢

4

2 回答 2

1

也添加这条路线:

match "signup" => "users#create", :via => "post"
于 2011-10-10T04:34:14.590 回答
1

routes.rb中可以添加

get "signup", to: "users#new"
post "signup", to: "users#create"
put "signup", to: "users#update"

并在注册表单中 - 检查signup_path

form_for(resource, as: resource_name, url: signup_path, html: {method: 'post'})

对于使用过 devise_for :users的其他读者,可以将路由定义为:

devise_scope :user do
  get "signup", to: "devise/registrations#new"
  post "signup", to: "devise/registrations#create"
  put "signup", to: "devise/registrations#update"
end

和注册表如上

通过添加此路由,即使在用户填写注册表时出现错误,您也可以使用您的命名路由,例如(注册、注册)。

于 2015-06-09T21:11:55.293 回答