ruby-on-rails – 在模型验证失败时使用自定义路由
我刚刚在我的Rails应用程序中添加了一个联系表单,以便站点访问者可以向我发送消息.该应用程序有一个消息资源,我已经定义了这个自定义路由,使URL更好,更明显:
map.contact '/contact',:controller => 'messages',:action => 'new' 当模型验证失败时,如何将URL保持为/ contact?目前,在验证失败时,URL会更改为/ messages. 这是我的messages_controller中的create方法: def create @message = Message.new(params[:message]) if @message.save flash[:notice] = 'Thanks for your message etc...' redirect_to contact_path else render 'new',:layout => 'contact' end end 提前致谢. 解决方法
一种解决方案是使用以下代码制作两个条件路由:
map.contact 'contact',:action => 'new',:conditions => { :method => :get } map.connect 'contact',:action => 'create',:conditions => { :method => :post } # Notice we are using 'connect' here,not 'contact'! See bottom of answer for explanation 这将使所有获取请求(直接请求等)使用“新”操作,并且帖子请求“创建”操作. (还有另外两种类型的请求:put和delete,但这些都与此无关.) 现在,在您创建消息对象更改的表单中 <%= form_for @message do |f| %> 至 <%= form_for @message,:url => contact_url do |f| %> (表单助手将自动选择发布请求类型,因为在创建新对象时这是默认值.) 应该解决你的烦恼. (这也不会导致地址栏闪烁其他地址.它从不使用其他地址.) . >解释为什么使用connect不是问题 . 编辑 如果你认为额外的路线有点乱(特别是当你经常使用它时),你可以创建一个特殊的方法来创建它们.这种方法不是很漂亮(可怕的变量名称),但它应该完成这项工作. def map.connect_different_actions_to_same_path(path,controller,request_types_with_actions) # Should really change the name... first = true # There first route should be a named route request_types_with_actions.each do |request,action| route_name = first ? path : 'connect' eval("map.#{route_name} '#{path}',:controller => '#{controller}',:action => '#{action}',:conditions => { :method => :#{request.to_s} }") first = false end end 然后像这样使用它 map.connect_different_actions_to_same_path('contact','messages',{:get => 'new',:post => 'create'}) 我更喜欢原来的方法…… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |