【问题标题】:Rails 3 route helpers in model not respecting sub-URI模型中的 Rails 3 路由助手不尊重子 URI
【发布时间】:2014-04-11 22:18:35
【问题描述】:

使用 Rails 3.2.13。

我已经安装了 Nginx 和 Unicorn 来从子 URI 为 Rails 应用程序提供服务。我有一些视图需要发送资源链接,因此我使用了模型中的路径帮助器:

def to_exhibit()
  return {
      :label => self.id,
      :name => self.name,
      :edit_path => Rails.application.routes.url_helpers.edit_vehicle_path(self),
  }
end

这将产生一个类似http://localhost:8080/vehicles/10/edit 的URL,但我真正想要的是http://localhost:8080/app/vehicles/10/edit(其中/app 是我的子URI)。这在直接从视图中调用 edit_vehicle_path 时效果很好。我之前通过创建自己的助手解决了这个问题:

module ApplicationHelper
  def self.sub_uri_path(path)
    root = Rails.application.config.relative_url_root
    return '%s%s' % [ root, path ]
  end
end

config.relative_url_root 在我的config/environment 文件中定义。这行得通,但是必须有一个正确的方法来做到这一点,而且我不想在一年后不可避免地忘记它的时候维护它。

【问题讨论】:

  • 如果对您有帮助,请回答正确。谢谢 :)

标签: ruby-on-rails ruby-on-rails-3 nginx unicorn


【解决方案1】:

你为什么不把你的路线包装到一个范围内?

scope Rails.env.production? ? '/app' : '/test' do
  resources :posts, :comments
  ...
end

http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

【讨论】:

  • 谢谢,但我不是必须对所有资源进行范围划分吗?如果我想在某个时候更改子 URI 怎么办?如果子 URI 在测试中与生产中不同怎么办?
  • 只有 url 会改变。你的链接助手会保持不变。对于测试/生产差异,您可以查看我的更新帖子
  • 是的,我更喜欢这样,但是 Unicorn 或 Nginx 配置中不应该有一种方法可以传播到 Rails 吗?
  • 我仍然想知道是否有系统级的解决方案来解决这个问题,但我越想越觉得,从配置中确定整个应用程序的范围是单行的,所以这很好。
  • 这就是我所做的:scope (Rails.application.config.respond_to?(:url_root) ? Rails.application.config.url_root: '/') do ...,其中config.url_root 可以在我的环境文件中定义。
【解决方案2】:

您可以使用 :script_name 参数来设置它:

Rails.application.routes.url_helpers.edit_vehicle_path(self, :script_name => '/app')

http://zergsoft.blogspot.jp/2014/04/using-non-root-mount-point-with-rails-3.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-03
    • 2012-10-27
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多