我运行一个具有多个域名的 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?
发布评论
评论(1)
如果这是一个控制器实例变量,那么您应该可以在控制器域和视图域中任何需要它的地方访问@website。如果您需要以相同的容量将某些内容推送到模型空间,您要么必须传递它,要么通过类似 model_helper 方法。
您可能会做的是在您的 Website 类上使用一种单例方法,例如:
然后在控制器中您可以执行以下操作:
这样您就可以在模型空间内的任何位置引用 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:
Then in the controller you can do things like:
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.