【问题标题】:Rails subdomains and default_scopeRails 子域和 default_scope
【发布时间】:2015-02-06 10:32:00
【问题描述】:

我有一个工作应用程序。我想添加将服务于同一应用程序但具有不同数据的子域。我在一个 Foo 表中添加了一个子域字段,外键指向这个 Foo 表,只要我希望数据按子域过滤,例如 Bar 表添加了一个 foo_id。

ApplicationController 有一个 before_filter 设置 @foo:

foos = Foo.where(subdomain: request.subdomain)
@foo = foos.first if foos.count > 0

我希望 Bar 模型有一个使用 @foo 的默认范围,这样我就不必更改我调用 Bar 的所有位置。

default_scope { where(foo: @foo) }

这对于无子域 url 非常有效,其中@foo 为 nil,应用程序仅显示 foo_id 为 NULL 的数据。但它不适用于子域,即使 pry 让我看到 @foo 设置正确,default_scope 仍然选择 NULL foo_id。

那么在模型范围内使用 AppController 中的实例变量是不可能的吗?

【问题讨论】:

    标签: ruby-on-rails scope subdomain


    【解决方案1】:

    在 Railscast 中回答 #388 http://railscasts.com/episodes/388-multitenancy-with-scopes

    使用 Foo 的类方法,跟踪 current_id,因此默认范围变为:

    default_scope { where(foo_id: Foo.current_id) }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-22
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多