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?
Or is there a nice way of 'casting' my Post objects into AdminUserPost's and OrdinaryUserPost's as appropriate?
EDIT:
This works as expected - provided you have a column called 'type' in the Post class. If your column is called something else, such as 'post_type' then you need to add:
self.inheritance_column = 'post_type'
In ALL the child models (AdminUserPost and OrdinaryUserPost in this example) and in the parent (Post).
Thanks,
Stephen.
Double check that the posts table has a column 'type' (string). If the AdminUserPosts and OrdinaryUserPosts are written to the table 'posts' and the type column is correct, you should get the subclass behavior you expect.
This works as expected - provided you have a column called 'type' in the Post class. If your column is called something else, such as 'post_type' then you need to add:
self.inheritance_column = 'post_type'
In ALL the child models (AdminUserPost and OrdinaryUserPost in this example) and in the parent (Post).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With