Bypassing automatic STI generation

1 view
Skip to first unread message

Fernando Perez

unread,
Mar 11, 2010, 9:26:39 AM3/11/10
to rubyonra...@googlegroups.com
Hi,

Let's say I have the following:

Product < AR
Memberships < Product

I know that the product with id 10 has its type column set to
"Membership", but still I'd like to treat it as a regular product.

So if I do: Product.find(10), Rails returns a Membership object.

Is it possible to tell rails to not care about STI and to simply return
a Product object?

Regards,
--
Posted via http://www.ruby-forum.com/.

Michael Pavling

unread,
Mar 11, 2010, 9:31:40 AM3/11/10
to rubyonra...@googlegroups.com
On 11 March 2010 14:26, Fernando Perez <li...@ruby-forum.com> wrote:
> Is it possible to tell rails to not care about STI and to simply return
> a Product object?

But it *is* a Membership object... ?:-/

But if you *have* to have it as a Product for some reason, you can use
the ActiveRecord::Base "becomes" method:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002334

Fernando Perez

unread,
Mar 11, 2010, 9:39:59 AM3/11/10
to rubyonra...@googlegroups.com
> But it *is* a Membership object... ?:-/
>
> But if you *have* to have it as a Product for some reason, you can use
> the ActiveRecord::Base "becomes" method:
> http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002334
It's a Membership indeed, but in the admin section of my app, I don't
need to recode a specific controller for memberships, they can use the
products_controller which is fine and defining :controller => "products"
won't do the trick as some actions cannot be shared.

#becomes is exactly what I was looking for, I didn't know about this
method and it's not featured in AWDWR 3rd Ed.

Thanks!

Michael Pavling

unread,
Mar 11, 2010, 9:48:21 AM3/11/10
to rubyonra...@googlegroups.com
On 11 March 2010 14:39, Fernando Perez <li...@ruby-forum.com> wrote:
>> But it *is* a Membership object... ?:-/
>>
> It's a Membership indeed, but in the admin section of my app, I don't
> need to recode a specific controller for memberships, they can use the
> products_controller which is fine and defining :controller => "products"
> won't do the trick as some actions cannot be shared.

Makes sense.

> #becomes is exactly what I was looking for, I didn't know about this
> method and it's not featured in AWDWR 3rd Ed.

Kewl. Glad to help.
AWDWR is a good book - but it's not all-encompassing... You need to
get familiar with navigating the Ruby and Rails API documentation to
find the rest of the cool stuff :-)

Reply all
Reply to author
Forward
0 new messages