在 Ruby on Rails 中定义命名空间模型的正确方法

发布于 2024-12-05 07:19:04 字数 308 浏览 1 评论 0原文

只是想知道在 Rails 中定义命名空间模型的正确方法是什么。我看到它有两种定义。在大多数库中,它们似乎都是这样定义的

module Fruit
  class Banana < ActiveRecord::Base
     ...
  end
end

,而 Rails 生成器似乎更喜欢这样。

class Fruit::Banana < ActiveRecord::Base
  ...
end

它们显然都可以工作,但有什么区别呢?哪个是首选?谢谢!

Just wondering what is the proper way to define a namespaced model in Rails. I've seen it defined in two ways. In most libraries they seem to be defined as such

module Fruit
  class Banana < ActiveRecord::Base
     ...
  end
end

whereas the Rails generator seems to prefer this

class Fruit::Banana < ActiveRecord::Base
  ...
end

They both obviously work but what is the difference? Which is preferred? Thanks!

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

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

发布评论

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

评论(3

樱花细雨 2024-12-12 07:19:04

它们并不相同,更详细的方式将实际定义模块,而更简短的方式将期望它已经被定义。

class Fruit::Banana; end

这将抛出一个NameError。但是,如果您

module Fruit; end
class Fruit::Banana; end

这样做,则不会引发错误。

They are not identical, the more verbose way will actually define the module, whereas the shorter way will expect it to be defined already.

class Fruit::Banana; end

That will throw a NameError. However if you do

module Fruit; end
class Fruit::Banana; end

it will not throw an error.

穿透光 2024-12-12 07:19:04

它们是相同的,但“更长”的版本允许您向模块添加其他内容。 更喜欢这样,因为我经常以这种方式将多个小东西打包到一个模块中。

They're the same, but the "longer" version lets you add other stuff to the module. I prefer that since I'll often package multiple small things into a module that way.

老娘不死你永远是小三 2024-12-12 07:19:04

它们是相同的,其次只是语法糖。

They are identical, second is just syntax sugar.

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