我刚刚在我的 Rails 应用程序中添加了一个联系表单,以便站点访问者可以给我发送消息。该应用程序具有 Message
资源,我定义了这个自定义路由以使 URL 更好更明显:
map.contact '/contact', :controller => 'messages', :action => 'new'
如何将 URL 保留为
/contact
当模型验证失败时?目前 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
提前致谢。
最佳答案
一种解决方案是使用以下代码创建两条条件路由:
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 请求(直接请求等)使用“new”操作,而 post 请求使用“create”操作。 (还有另外两种类型的请求:放置和删除,但这些在这里无关紧要。)
现在,在您创建消息对象的表单中更改
<%= form_for @message do |f| %>
到
<%= form_for @message, :url => contact_url do |f| %>
(表单助手会自动选择 post 请求类型,因为这是创建新对象时的默认类型。)
应该能解决你的烦恼。
(这也不会导致地址栏闪烁另一个地址。它从不使用另一个地址。)
.
map.name_of_route 只引用路径。因此,第二条路线不需要新的命名路线。您可以使用原始的,因为路径是相同的。所有其他选项仅在新请求到达 rails 并且需要知道将其发送到哪里时使用。
.
编辑
如果您认为额外的路由有点困惑(尤其是当您更频繁地使用它时),您可以创建一个特殊的方法来创建它们。这种方法不是很漂亮(可怕的变量名),但它应该可以完成这项工作。
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'})
不过我更喜欢原来的方法...
关于ruby-on-rails - 在模型验证失败时使用自定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1083798/