同一应用程序上每个域名一项配置。如何轻松访问模型中的配置值?

发布于 2024-09-03 08:13:33 字数 539 浏览 1 评论 0 原文

我运行一个具有多个域名的 Ruby on Rails 网站。我在数据库中有一个“网站”表,用于存储与每个域名相关的配置值:

网站
- 域名
- 姓名
- 标语
- 管理员电子邮件
- 等等...

目前,我在 ApplicationController 中的每个请求开始时(before_filter)加载网站对象:

@website = Website.find_by_domain(request.host)

问题是当我需要从模型的方法访问 @website 对象时。我想避免到处传递@website。最好的解决方案是有类似于 APP_CONFIG 的东西,但每个域名。

def 样本_模型_属性
- - “#{@website.name} 是一个很棒的网站!”
结束

你会怎么做?

I run a Ruby on Rails website that have multiple domain names. I have a "Website" table in the database that stores the configuration values related to each domain name:

Website
- domain
- name
- tagline
- admin_email
- etc...

At the moment, I load the website object at the start of each request (before_filter) in my ApplicationController:

@website = Website.find_by_domain(request.host)

The problem is when I need to access the @website object from my model's methods. I would like to avoid to have to pass @website everywhere. The best solution would be to have something similar to APP_CONFIG but per domain name.

def sample_model_property
- - "#{@website.name} is a great website!"
end

How would you do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烏雲後面有陽光 2024-09-10 08:13:34

如果这是一个控制器实例变量,那么您应该可以在控制器域和视图域中任何需要它的地方访问@website。如果您需要以相同的容量将某些内容推送到模型空间,您要么必须传递它,要么通过类似 model_helper 方法。

您可能会做的是在您的 Website 类上使用一种单例方法,例如:

class Website < ActiveRecord::Base
  cattr_accessor :current_website
end

然后在控制器中您可以执行以下操作:

before_filter :load_current_website

def load_current_website
  Website.current_website = Website.find_by_domain(request.host)
end

这样您就可以在模型空间内的任何位置引用 Website.current_website 并且事物应该同步。请注意,这可能不是完全线程安全的,在使用它之前应该在类似生产的环境中进行广泛的测试。

If this is a controller instance variable, then you should have access to @website everywhere you require it both the Controller and View domains. If you need to push something through to the Model space in the same capacity, you either have to pass it, or hack it in via something like the model_helper method.

What you might do instead is use a kind of singleton method on your Website class, for instance:

class Website < ActiveRecord::Base
  cattr_accessor :current_website
end

Then in the controller you can do things like:

before_filter :load_current_website

def load_current_website
  Website.current_website = Website.find_by_domain(request.host)
end

That way you can refer to Website.current_website anywhere within the model space and things should be in sync. Note that this may not be entirely thread safe and should be tested extensively in a production-like environment before using it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文