Best way to blueprint the abstract class of a single table inheritance model?

57 views
Skip to first unread message

Ary Borenszweig

unread,
Jun 17, 2011, 4:09:32 AM6/17/11
to Machinist Users
Hi,

Say I have a Place class with a type column for STI and Country and
Province as subclasses. Every place has a parent and a name. So I
write:

Place.blueprint do
code
name
type { [Country, Province].sample.to_s }
end

Country.blueprint do
end

Province.blueprint do
parent { Country.make }
end

This doesn't work because the type gets overwritten on the Place
blueprint if I do Country.make. I can remove it:

Place.blueprint do
code
name
end

But then I can't blueprint a Place anymore because it won't have a
type.

What I'd like to accomplish is to call Place.make and get Country.make
or Province.make randomly.

Any suggestions?

A solution could be:

def Place.make
[Country, Province].sample.make
end

but then I need to do the same for make_unsaved and plan and it looks
kind of hacky... :-P

Any ideas?

Thanks!

Pete Yandell

unread,
Jun 19, 2011, 8:32:19 AM6/19/11
to Machinist Users
Hi Ary,

You definitely shouldn't try to set the type attribute in the
blueprint, any more than you'd do so on an ActiveRecord model.

make_unsaved actually calls make, so just defining Place.make like
that should work. (You won't get plan, but nobody uses that anyway.)

If I was you, though, I'd just write a helper method, and call
Machinist from that. If I was reading your tests, it wouldn't be
obvious to me that Place.make will actually return a subclass of
place. Better to make it explicit.

Chris Corbyn

unread,
Jun 19, 2011, 8:37:24 AM6/19/11
to machini...@googlegroups.com
> If I was you, though, I'd just write a helper method, and call
> Machinist from that. If I was reading your tests, it wouldn't be
> obvious to me that Place.make will actually return a subclass of
> place. Better to make it explicit.

This. +1

Reply all
Reply to author
Forward
0 new messages