Single Table Inheritance questions


#1

I’m a rails noob and I’ve been playing around with creating an app
that will display services provided at various schools.

At first, I had a schools table, then I decided that I wanted an
agencies table as well. They share many attributes (address, etc) and
differ only in a few (level, e.g., elementary, middle, etc). So I
decided I would use organizations as my base. I have a “type” column.

I started by generating a scaffold: Organization Admin.

In my organization model, I added School < Organization and Agency <
Organization.

That gives me generic organizations admin stuff, but there’s no “type”
field in the new organization form.

I tried generating a scaffold for School Admin, but since there’s no
table for schools, rails didn’t like that.

So if I want create a new school entry, how should I go about that?

Thanks!


#2

Hi,

I am fairly much a noob myself here but this is the way I have done it.

I did a script/generate controller for each of my subclasses and copied
in
the
views to the corresponding directories. Then copy in all the methods
from
the base
class controller to the subclass controllers. Edit all the references
from
Organisation to
school in your School controller and that should do it.

Rails will handle the type column for you, you won’t have to set its
value.

Hope that helps,

Keith


#3

Thanks, but I’m still not clear on how I would create a new school in
my app. Right now, there’s a “new organization” link on the admin page
(created by the scaffold command). What do I need to do to make a “new
school” and “new agency” link (and have them do the right mojo with
the “type” attribute).


#4

Ok, it depends on how you are using scaffold. Do you have scaffold
:organisation in your organisation
controller or did you run script/generate scaffold organisation?

If you did the latter you probably have a folder under views called
Organisations, if you create a school
controller it will need a folder under views called schools. You will
need a
list, show, edit, new rhtml file
for each function in that folder.

To create links between these you will need to add some navigation code
to
your layouts. You can either do this by
creating a nav partial or by using the same layout for all three
controllers
and placing the nav in the layout. If you made a partial called
_nav.rhtml
and placed it in views/shared you could call it from each layout file
like
so:
<%= render :partial => ‘shared/nav’ %>

If you want to use the one layout with each controller you put a link in
the
controller like this,

layout ‘global’

where you have a layout file called global.rhtml in your views/layouts
folder.

Keith


#5

Your right and to be honest I’m not sure.

As I said I’m pretty much a noob myself with only about 6 weeks of
Rails.

But this is what has worked for me.

Keith


#6

Is it possible to do all this without duplicating everything. Doesn’t
sound very DRYish…