开发者

How does the :type field get populated in Single Table Inheritance?

开发者 https://www.devze.com 2023-01-28 15:13 出处:网络
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 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 work开发者_JS百科s 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".


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.


@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

0

精彩评论

暂无评论...
验证码 换一张
取 消