在渲染期间由控制器插入的URL前缀

时间:2014-10-17 03:05:34

标签: ruby-on-rails ruby-on-rails-4

我在链中有一些简单的控制器和视图,在链的末尾有静态html页面,因此:

ControllerA - > ControllerB - >的index.html

Controller A重定向到Controller B中的一个动作,然后再渲染html。 控制器C是第三个控制器,只能通过html中href的链接访问。

如果浏览器直接访问html页面,请访问myDomain.com/index.html'然后渲染其基于Bootstrap的HTML5页面,其中的所有链接都能完美运行。

但是,使用Rails链会导致html页面完美呈现,但许多链接不起作用,因为GET中的URL以下列方式出错:

ActionController :: RoutingError(没有路由匹配[GET]" / controllerB / home / ControllerC / desiredAction")

因此,问题是html页面中的所有链接都会被添加到呈现html的控制器的最后一个激活的操作路径。当然,不存在这样的路线。

我相信,从以前的实验中,重定向而不是渲染会产生同样的问题。

从控制器呈现的静态html页面链接会影响网址的形成?

routes.rb会尝试路由操作(也许我误解了文档):

Rails.application.routes.draw do
    # You can have the root of your site routed with "root"
    root :controller => 'static', :action => '/public/index.html'

    # Example of regular route:
    #   get 'products/:id' => 'catalog#view'
    get 'controllera/actiona'
    get 'controllera/actionb'

    get 'controllerb/home/:id', to: 'controller_b#home'
    get 'controllerc/desiredAction', to: 'controller_c#desiredAction'
end

并在静态页面中触发html:

    <a href="controllerc/desiredAction" title="My title">

2 个答案:

答案 0 :(得分:1)

在静态html页面中,只需定义与控制器,操作和ID的链接,并将id的值设置为nil

例如

<%= link_to "Some Page", :controller => "your_destination_controller", :action => "your_action", :id => nil %>
然后一切都会好起来的。如果您仍然收到错误,请评论您的问题。

答案 1 :(得分:0)

答案是html中的引用链接应指定绝对而不是相对路径:

    # note: the path now begins with a '/', making it absolute
    <a href="/controllerc/desiredAction" title="My title">

以前,如果没有'/'前缀,则路径被视为 relative 到执行渲染的当前控制器操作。使用'/'前缀,路径的第一个组件现在是所需的目标控制器。

这适用于使用控制器呈现html或通过浏览器直接访问html页面。