Forum: Ruby on Rails Single table inheritance and find(:all) in parent

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
stephen O'D (Guest)
on 2009-04-08 23:38
(Received via mailing list)
I understand how STI works, in that I have say a Post model that
contains posts on a forum and several sub-posts like
'ordinaryUserPost' and 'adminUserPost' etc.

Now, I want to define the same method in each of the sub-posts, but
the method would do something different in each case, eg

class Post < ActiveRecord::Base
end

class AdminUserPost < Post
  def background_color
    'rockstar red'
  end
end

class ordinaryUserPost < Post
  def background_color
    'pale blue'
  end
end

(yes its a silly example).  Now in my thread controller I do Post.find
(:all) and it gives me a list of posts I need to render, but they are
'Post' objects, not AdminUserPost or OrdinaryUserPost - so I cannot
just get my background_color method!  I would have to do a find on
each type of user post separately ...

Is there anyway I can do:

Post.find(:all)

And in the resultant array get a list of AdminUserPost and
OrdinaryUserPost objects instead of Post objects?

Thanks,

Stephen.
Frederick C. (Guest)
on 2009-04-09 02:42
(Received via mailing list)
On Apr 8, 8:37 pm, "stephen O'D" <removed_email_address@domain.invalid> wrote:
> Is there anyway I can do:
>
> Post.find(:all)
>
> And in the resultant array get a list of AdminUserPost and
> OrdinaryUserPost objects instead of Post objects?
>
That's the way it should work out of the box. Would be interesting to
see the data / code that results in this not happening.

Fred
stephen O'D (Guest)
on 2009-04-10 20:35
(Received via mailing list)
>
> That's the way it should work out of the box. Would be interesting to
> see the data / code that results in this not happening.

I was being stupid - put my type column was actually called post_type,
and I added self.inheritance_column = ''post_type' in all the child
classes, but forgot the parent!
This topic is locked and can not be replied to.