[英]Organizing namespaced and related models in Rails
I'm having a bit of trouble organizing a Rails project and its models regarding folder structure and conventions and I don't seem to find anything related to this anywhere. 我在组织有关文件夹结构和约定的Rails项目及其模型时遇到了一些麻烦,而且我似乎在任何地方都找不到与此相关的任何东西。
Let's say I want to create a Cinema
model, this Cinema
has many Cinema::Location
models and each Cinema::Location
has many Cinema::Location::Movie
screenings, on top of that each movie might have a Cinema::Location::Movie::Review
, not to mention each review might have comments... 假设我要创建一个Cinema
模型,该Cinema
具有许多Cinema::Location
模型,每个Cinema::Location
具有许多Cinema::Location::Movie
放映,此外,每部电影都可能具有Cinema::Location::Movie::Review
,更何况每个评论可能都有评论...
My folder structure would look something like this: 我的文件夹结构如下所示:
This is an organized solution, but at the same time, it doesn't look good, it's worse if we talk about the tables ( cinema_location_movie_review_comment_replies
). 这是一个有组织的解决方案,但同时看起来也不是很好,如果我们谈论这些表( cinema_location_movie_review_comment_replies
),那就更糟了。
One thing I could do is to organize the models like this: Cinema::Location
for the location and Location::Movie
for movies, Movie::Review
for reviews, etc. 我可以做的一件事就是组织这样的模型: Cinema::Location
表示位置,而Location::Movie
表示电影, Movie::Review
进行评论等。
Folder structure would look like this: 文件夹结构如下所示:
This solves the problem with the table names ( location_movie
or movie_review
). 这解决了表名( location_movie
或movie_review
)的问题。
Are there any conventions regarding multi-level namespaced models? 是否有关于多层命名空间模型的约定?
Have you asked yourself why you're nesting your models at all? 您是否曾问过自己,为什么根本要嵌套模型? It looks to me like you're trying to shoehorn namespaces into performing logic that's better left to associations. 在我看来,您正在尝试刺破名称空间来执行最好由关联决定的逻辑。
If you check out the ActiveRecord associations docs , you'll notice that in the first example, Book
and Author
are top-level models -- there's no mention of Book::Author
or anything like that. 如果您查看ActiveRecord关联文档 ,您会注意到在第一个示例中, Book
和Author
是顶级模型-没有提到Book::Author
或类似的东西。 There's your convention. 有你的约定。
As your application grows more bigger and more complex, cases may arise where model namespacing is appropriate (say, resources specific to different user types), but I don't think it is here. 随着您的应用程序变得越来越大和越来越复杂,可能会出现适合使用模型命名空间的情况(例如,特定于不同用户类型的资源),但我认为这并不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.