【发布时间】:2016-04-16 19:30:28
【问题描述】:
我正在根据 Ryan Bigg 的“Multitenancy with Rails”一书中的想法创建一个多租户应用程序。在本书中,租户有自己的子域。这种方法不适用于我的情况,因此我尝试通过帐户名称来确定范围。
所以我想要http://myapp.mydomain.com/account-name/,而不是像http://account-name.myapp.com 这样的URL。子域是为应用程序本身保留的,因为我希望能够在我的域中拥有多个应用程序。
这是我的路线.rb:
scope module: 'accounts' do
resources :customers do
resources :notes
end
end
为了实现我的目标,我尝试按照rubyonrails.com上的路由指南(第4.5章中的最后一个代码sn-p),并将上面的代码更改为:
scope ':slug', module: 'accounts' do
resources :customers do
resources :notes
end
end
slug 是数据库中accounts 表中的一个属性,因此如果一个帐户名为“我的企业”,则它通常是“我的企业”。
此更改似乎纠正了我的路线:
customers GET /:slug/customers(.:format)
.. 但它似乎也破坏了我的网站,因为没有从数据库中获取 slug。我似乎无法理解scope':slug', module: 'accounts' 的工作原理。 Rails 是否应该自动将 :slug 识别为 Account 表的属性?如果没有,谁能帮我找到在我的网址中使用该帐户的 slug 的方法?
我已经用谷歌搜索了几天,并在 Stackoverflow 上阅读了许多答案。没有任何帮助,因此非常感谢任何指针。 :-)
编辑:
相关的控制器是这样设置的:
controllers/accounts/base_controller.rb
controllers/accounts/customers_controller.rb
controllers/accounts/products_controlelr.rb
controllers/accounts_controller.rb
controllers/application_controller.rb
accounts_controller.rb 此时只有 new 和 create 操作。
accounts/base_controller.rb 如下所示:
module Accounts
class BaseController < ApplicationController
before_action :authorize_user!
def current_account
@current_account ||= Account.find_by_slug(params[:slug])
end
...
end
end
我将此添加到我的帐户模型中:
def to_param
slug
end
在我尝试在我的路线中实施scope ':slug' 之前,当登录用户并导航到 myapp.mydomain.com/dashboard 并导航到即 myapp.mydomain.com/customers 时,一切都有效。现在它适用于 myapp.mydomain.com/account-name/dashboard,但是当我尝试导航到使用像 new_customer_path 这样的帮助器的视图时,我得到了错误:
没有路由匹配 {:action=>"show", :controller=>"accounts/customers", :id=>nil, :slug=>#
我希望这能让我的问题更清楚。 :-)
【问题讨论】:
-
所以你想要一个看起来像
http://myapp.mydomain.com/account-name/customers的网址? -
是的,“客户”是帐户模块中我的控制器的一个示例
标签: ruby-on-rails routing multi-tenant scoping