在命名空间中处理命名空间模型(类) [英] Handling namespace models (classes) in namespace
问题描述
我使用Ruby on Rails 3,我想在命名空间中处理模型(类)命名空间。也就是说,如果我有一个名为 NS1 的命名空间和名为 NS2 的命名空间的子命名空间,我想在 NS2 。
I am using Ruby on Rails 3 and I would like to handle models (classes) namespaces within namespaces. That is, if I have a namespace named NS1 and a "sub-namespace" of that namespace named NS2, I would like to handle models (classes) in NS2.
如果我运行 scaffold
rails generate scaffold ns1/ns2/Article id:integer title:string
它将生成以下模型文件:
it will generate following model files:
models/ns1/ns2/article.rb file
models/ns1/articles.rb
models / ns1 / articles.rb
包含:
module Ns1::Articles
def self.table_name_prefix
'ns1_articles_'
end
end
models / ns1 / articles.rb
文件?如何以及为什么我可以使用它?
What is the models/ns1/articles.rb
file? How and why can I use that? Have you advices about using that?
一般来说,在使用Ruby on Rails的命名空间中处理组合类是什么是最好的方法?
And, in general, what is "the best" way to handle "composed" classes in namespaces using Ruby on Rails?
推荐答案
models / ns1 / articles.rb
models/ns1/articles.rb
基本上是为该命名空间下的所有模型类设置表名前缀。这就是它的用途。在这里(在一个单独的文件中),更干燥,而不是在该命名空间下的每个模型类中设置前缀。
is basically setting the table name prefix for all the model classes under that namespace. Thats its use. It's more DRY'ish to do in there (in a single file), rather than setting the prefix in every model class under that namespace.
我不是一个大粉丝在我的模型中使用命名空间。但是,您可以参考以下文章,以更好地了解在模块中使用命名空间。
I am not a big fan of using namespaces in my models. However you could refer to the following articles to gain a better understanding about using namespaces in modules.
- ActiveRecord: Can haz namespaces?
- Namespaced models and controllers
在模型中使用命名空间的一些替代方法
Some alternatives to using namespaces in models
- Namespaced models
- A simple alternative to namespaced models
希望这有助于。
这篇关于在命名空间中处理命名空间模型(类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!