Ruby-on-rails 处理命名空间中的命名空间模型(类)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5852626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling namespace models (classes) in namespace
提问by user502052
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 NS1and a "sub-namespace" of that namespace named NS2, I would like to handle models (classes) in NS2.
我正在使用 Ruby on Rails 3,我想处理命名空间内的模型(类)命名空间。也就是说,如果我有一个名为NS1的命名空间和一个名为NS2的命名空间的“子命名空间” ,我想在NS2 中处理模型(类)。
If I run a 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
The models/ns1/articles.rbcontains:
其中models/ns1/articles.rb包含:
module Ns1::Articles
def self.table_name_prefix
'ns1_articles_'
end
end
What is the models/ns1/articles.rbfile? How and why can I use that? Have you advices about using that?
models/ns1/articles.rb文件是什么?我如何以及为什么可以使用它?你有关于使用它的建议吗?
And, in general, what is "the best" way to handle "composed" classes in namespaces using Ruby on Rails?
而且,一般来说,使用 Ruby on Rails 处理命名空间中“组合”类的“最佳”方法是什么?
采纳答案by thekindofme
The
这
models/ns1/articles.rb
模型/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.
基本上是为该命名空间下的所有模型类设置表名前缀。这就是它的用途。在那里(在单个文件中)做更 DRY'ish,而不是在该命名空间下的每个模型类中设置前缀。
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.
我不喜欢在我的模型中使用命名空间。但是,您可以参考以下文章以更好地了解在模块中使用命名空间。
Some alternatives to using namespaces in models
在模型中使用命名空间的一些替代方法
Hope this helps.
希望这可以帮助。

