:type 字段如何在单表继承中填充?
我之前问了一个关于如何在我正在构建的用于管理内容的简单应用程序中构建数据的问题。答案是查看单表继承,我认为这将是门票。
我读过很多例子,但似乎总是被遗漏的一件事是 :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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
猜测您将所有“站点”、“博客”、“照片”信息存储在内容表中。当您通过
Content.new
启动任何对象时,它没有为类型字段分配任何值。但是,如果您从“站点”、“博客”或“照片”启动任何类,这些类实际上是从“内容”模型继承的-
Site.new
或Site.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
orSite.create
then it automatically assigns model_name(in this case-Site
) in the type fieldSimilarly if you do
Blog.new
it will assign Blog in type column and so on.@jyoseph,是的,你完全正确。您可以在新的编辑视图中添加一个下拉列表,其中将包含类型,在您的情况下为“站点”、“博客”、“照片”。您还可以在您的应用程序帮助程序文件中创建一个帮助程序,如下所示
,然后在您的 content/new.html.erb 中您可以
尝试一下,这可能会起作用。
以防万一,如果有人想了解有关 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
and then in your contents/new.html.erb you can do
Try it, this might work.
Just in case if anyone wants to know more about STI visit my Blog