rails-根模型或应用程序模型 [英] rails - root model or application model

查看:68
本文介绍了rails-根模型或应用程序模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是环顾四周,发现有一个应用程序控制器,但没有应用程序模型.

I was just looking around rails and noticed there is an app controller but no app model.

rails中是否没有根模型?如果没有的话,您在每个模型中都放置了一段代码.

Is there no root model in rails ? if not where do you put a piece of code that needs to be in every model.

谢谢亚历克斯

推荐答案

没有什么说您的控制器必须继承ApplicationController的子类,但这通常是标准的,因为绝大多数的rails应用程序都使用layout功能(可能会因每个控制器而异),因此与其强迫每个没有布局的稀有版本关闭每个控制器的布局(layout nillayout false),它们是一种抽象"的方法,您可以打开或关闭控制器功能.轻松适用于您的整个应用程序.

Nothing says your controllers have to subclass ApplicationController but it generally is the standard because the vast majority of rails applications make use of the layout capabilities (which can vary on each controller), so instead of forcing the rare ones without layouts from turning the layout off (layout nil or layout false) for each controller, they make an 'abstract' one that you can turn controller features on and off easily for your whole application.

现在对于模型,您可以为所有模型创建一个ApplicationModel进行子类化,但是要考虑两件事:

Now for models, you could create an ApplicationModel for all of your models to subclass, but there are two things to think about:

  1. ActiveRecord通常会检测您何时将已经子类化的ActiveRecord::Base子类化,并使用它来打开STI(单表继承).
  2. ApplicationModel将是一个实际模型,该模型应该在数据库中具有一个表.这可能会导致问题.
  1. ActiveRecord normally detects when you subclass an already subclassed ActiveRecord::Base and uses this to turn STI (single table inheritance) on.
  2. ApplicationModel will be an actual model that is expected to have a table in your database. This can lead to problems down the line.

要解决这两个问题,必须将abstract_class设置为true才能使ActiveRecord正常运行.

To fix these two problems, you have to set abstract_class to true for ActiveRecord to properly function.

class ApplicationModel < ActiveRecord::Base
  self.abstract_class = true
end

与抽象的ActionController相比,abstract_class 必须设置为true,这意味着开发人员必须知道他们无法从ApplicationModel中删除此行.有了ApplicationController,您几乎可以做任何想做的事.

In contrast to an abstract ActionController, abstract_class must set to true which means the developer must know they cannot remove this line from ApplicationModel. With ApplicationController you can do pretty much whatever you want to it.

这篇关于rails-根模型或应用程序模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆