我刚刚在我的Rails应用程序中添加了一个联系表单,以便站点访问者可以向我发送消息.该应用程序有一个Message资源,我已经定义了这个自定义路由,使URL更好,更明显:
map.contact '/contact', :controller => 'messages', :action => 'new'
Run Code Online (Sandbox Code Playgroud)
如何/contact在模型验证失败时保留URL ?目前,URL /messages在验证失败时更改为.
这是create我的方法messages_controller:
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
Run Code Online (Sandbox Code Playgroud)
提前致谢.
一种解决方案是使用以下代码制作两个条件路由:
map.contact 'contact', :controller => 'messages', :action => 'new', :conditions => { :method => :get }
map.connect 'contact', :controller => 'messages', :action => 'create', :conditions => { :method => :post } # Notice we are using 'connect' here, not 'contact'! See bottom of answer for explanation
Run Code Online (Sandbox Code Playgroud)
这将使所有获取请求(直接请求等)使用"新"操作,并且帖子请求"创建"操作.(还有另外两种类型的请求:put和delete,但这些都与此无关.)
现在,在您创建消息对象更改的表单中
<%= form_for @message do |f| %>
Run Code Online (Sandbox Code Playgroud)
至
<%= form_for @message, :url => contact_url do |f| %>
Run Code Online (Sandbox Code Playgroud)
(表单助手将自动选择后置请求类型,因为在创建新对象时这是默认值.)
应该解决你的烦恼.
(这也不会导致地址栏闪烁其他地址.它从不使用其他地址.)
.
.
编辑
如果你认为额外的路线有点乱(特别是当你经常使用它时),你可以创建一个特殊的方法来创建它们.这种方法不是很漂亮(可怕的变量名称),但它应该完成这项工作.
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
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它
map.connect_different_actions_to_same_path('contact', 'messages', {:get => 'new', :post => 'create'})
Run Code Online (Sandbox Code Playgroud)
我更喜欢原来的方法......
| 归档时间: |
|
| 查看次数: |
1903 次 |
| 最近记录: |