【问题标题】:Removing url scope segment with url helpers使用 url 助手删除 url 范围段
【发布时间】:2013-06-06 22:54:16
【问题描述】:

我正在编写一个使用 AngularJS 的应用程序,因此该应用程序设置为将所有请求路由到 Angular 接管的主主页。然后在 Angular 用于检索数据的 api 范围内定义所有路由。但是,如果用户导航到具有正常 URL 的页面,那么当它重定向到主页时,它会保留该 URL,然后 Angular 会使用该 URL 来加载正确的状态。

我现在想要做的是能够在 Rails 中使用 URL 助手来生成我的 URL,但生成的 URL 不包含范围的 /api。有什么办法可以解决这个问题吗?

routes.rb有点像

scope "/api", shallow_path: "/api" do
    ... normal stuff here ...
end

如果我尝试使用其中一个助手,

meeting_url(@meeting, subdomain: "test")

它生成的网址是

http://test.domain.com/api/meetings/1

有没有办法让我去掉/api

【问题讨论】:

    标签: ruby-on-rails-3 angularjs rails-routing


    【解决方案1】:

    我不相信有内置的方法可以做到这一点。

    但是,您使用的是 ruby​​,所以有很多方法可以做您想做的事。

    一种方法,因为你在自己的应用程序中,是做猴子补丁String

    class String
      def no_api
        self.gsub(/\/api/, '')
      end
    end
    
    meeting_url(@meeting, subdomain: 'test').no_api #=> http://test.domain.com/meetings/1
    

    如果您觉得不妥,您可以在 ApplicationController 或辅助模块中定义一个方法:

    def no_api(url)
      url.gsub(/\/api/, '')
    end
    

    等等。等等等等。

    【讨论】:

    • 我认为这可能是唯一的方法。只需要这样做:)干杯:)
    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2022-08-02
    • 1970-01-01
    • 2011-06-16
    相关资源
    最近更新 更多