一个解决办法是,以与这两个条件的路线下面的代码:
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
这将使所有get请求(直接请求等)使用“新”的行动,并发布请求的“创建”行动。 (还有其他两种类型的请求:put和delete,但这些都无关紧要这里)。现在
,形式要在其中创建的消息对象变化
<%= form_for @message do |f| %>
到
<%= form_for @message, :url => contact_url do |f| %>
(表单助手会自动选择发布请求类型,因为这是创建新对象时默认的。)
应该解决你的麻烦。
(这也不会导致地址栏闪烁的其他地址。它绝不会使用另一个地址。)
。
- 解释为什么使用连接在这里没有问题 map.name_of_route引用JUST THE PATH。因此,您不需要为第二条路线设置新的命名路线。您可以使用原来的路径,因为路径是相同的。所有其他选项仅在新请求达到导轨时使用,并且需要知道将它发送到何处。
。
编辑
如果您认为额外的途径使有点乱(特别是当你使用它更多的时候),你可以创建一个特殊的方法来创建它们。这种方法不是很漂亮(可怕的变量名称),但它应该完成这项工作。
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'})
我喜欢,虽然原来的方法...
不会工作,错误不会保留在对象上 – 2009-07-05 10:47:02
我也认为这是一个非常丑陋的解决方案......请参阅我的解决方案。 – 2009-07-05 13:28:58