问题描述
我对Rails还是陌生的,并且很难理解路径系统在Rails中的工作方式。
Im still new to Rails and have a hard time understanding how the path system works in Rails.
在我的route.rb中,我为注册创建了别名:
In my routes.rb i create an alias for signup:
match 'signup' => 'user#new'
resource :user, :controller => 'user'
操作在那里,转到/ signup会显示正确的操作。到目前为止,一切都很好。
The action is there and going to /signup shows the correct action. So far so good.
现在,当我提交我的注册表单时,它会像往常一样使用POST运行create操作。这就是即时通讯卡住的地方。
Now, when i submit my signup form it runs the create action with POST as usual. And here is where im stuck.
如果注册失败,我想再次向用户提供注册表单。一种选择是进行新渲染,但这会将用户带到/ user而不是/ signup。
If the signup fails, i would like to present the user with the signup form again. One option would be to do a render "new", but that takes the user to /user instead of /signup.
UserController
class UserController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to root_url
else
render "new"
end
end
end
任何帮助表示赞赏!
更新-解决方案
为/ signup添加了2个匹配路由,使用:via option
Added 2 match routings for /signup, using the :via option
match 'signup' => 'user#new', :as => :signup, :via => 'get'
match 'signup' => 'user#create', :as => :signup, :via => 'post'
通过这种方式,应用程序知道在发布到/ signup时应运行create动作,
This way the application knows that when posting to /signup it should run the create action, and when http method is get, it uses the new action.
控制器标记与上面发布的相同。
Controller markup is the same as posted above.
推荐答案
尝试在路由中添加 :as
:
match 'signup' => 'user#new', :as => :signup
然后执行
redirect_to signup_url
在您的控制器中。
对我有用。我仍然不知道为什么。也许其他人有解释。
That worked for me. I still don't know why. Maybe someone else has an explanation.
这篇关于Rails渲染路线路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!