如何从控制器正确渲染名为route的rails?
routes.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
user_controller.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
它转到/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"}
由于
答案 0 :(得分:1)
还添加此路线:
match "signup" => "users#create", :via => "post"
答案 1 :(得分: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
如上所述注册形式。
通过添加此路由,即使在用户填写注册表单时出现一些错误,也可以使用命名路由,如(注册,注册)。