:type 字段如何在单表继承中填充?

发布于 2024-10-04 22:35:11 字数 416 浏览 7 评论 0原文

我之前问了一个关于如何在我正在构建的用于管理内容的简单应用程序中构建数据的问题。答案是查看单表继承,我认为这将是门票。

我读过很多例子,但似乎总是被遗漏的一件事是 :type 列实际上是如何填充的?我是否包含一个带有下拉菜单的表单字段,以便用户可以选择类型?

我相信我现在完全理解 STI 的工作原理(类型字段采用类名),但仍然缺少一些非常基本的东西(并且可能非常明显,但我缺少它)。有人可以帮我补一下吗?

我有一个像这样的内容表:

id
type
name
desc

不同的类型是“网站”、“博客”、“照片”。

I asked a question earlier about how to structure the data in a simple app I am building to manage content. The answer was to look at Single Table Inheritance and I think it's going to be the ticket.

I've read quite a few examples but one thing that always seems to be left out is how the :type column is actually populated? Do I include a form field w/ a drop down so the user can select the types?

I believe I fully understand how STI works now (the type field takes on the class name) but am still missing something very basic (and probably very obvious, but I'm missing it). Can someone fill me in?

I have a content table like so:

id
type
name
desc

And the different types would be "Site", "Blog", "Photo".

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

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

发布评论

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

评论(2

乖乖兔^ω^ 2024-10-11 22:35:11

猜测您将所有“站点”、“博客”、“照片”信息存储在内容表中。当您通过 Content.new 启动任何对象时,它没有为类型字段分配任何值。

但是,如果您从“站点”、“博客”或“照片”启动任何类,这些类实际上是从“内容”模型继承的-
Site.newSite.create 然后它会自动在类型字段中分配 model_name(在本例中 - Site

类似地,如果您这样做 Blog.new 它将在类型列中分配 Blog 等等。

Guessing that you stores all "Site", "Blog", "Photo" information in contents table. When you initiates any object by Content.new, it does not have assigned any value to type field.

But if you initiate any class from "Site", "Blog" or "Photo" which have been actually inherited from "Content" model by-
Site.new or Site.create then it automatically assigns model_name(in this case- Site) in the type field

Similarly if you do Blog.new it will assign Blog in type column and so on.

遮了一弯 2024-10-11 22:35:11

@jyoseph,是的,你完全正确。您可以在新的编辑视图中添加一个下拉列表,其中将包含类型,在您的情况下为“站点”、“博客”、“照片”。您还可以在您的应用程序帮助程序文件中创建一个帮助程序,如下所示

def content_type
   return ["Site", "Blog", "Photo"]
end

,然后在您的 content/new.html.erb 中您可以

<p>
    <%= f.label :type %><br />
    <%= f.select :type, content_type %>
</p>

尝试一下,这可能会起作用。

以防万一,如果有人想了解有关 STI 的更多信息,请访问 我的博客

@jyoseph, yes you are absolutely correct. You can add a drop-down in you new and edit view which will hold the types, in your case "Site", "Blog", "Photo". You can also make a helper in your Application Helper file as follows

def content_type
   return ["Site", "Blog", "Photo"]
end

and then in your contents/new.html.erb you can do

<p>
    <%= f.label :type %><br />
    <%= f.select :type, content_type %>
</p>

Try it, this might work.

Just in case if anyone wants to know more about STI visit my Blog

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