Is it possible to set-up a scope on a single table inheritance that returns the subclass?
For example:
class Post < ActiveRecord::Base
scope :sticky, -> { where(type: 'StickyPost') }
end
class StickyPost < Post
end
Now, when I call sticky
on a collection of posts I get a collection of StickyPost
instances.
But when I call posts.sticky.build
, the type
is set to StickyPost
, but the class still is Post
.
posts.sticky.build
=> #<Post id: nil, message: nil, type: "StickyPost", created_at: nil, updated_at: nil>
Update
Apparently this works.
posts.sticky.build type: 'StickyPost'
=> #<StickyPost id: nil, message: nil, type: "StickyPost", created_at: nil, updated_at: nil>
Which is strange, since the scope already sets the type, it seems a bit redundant. Any way to set this behaviour in the scope?
StickyPost
or another subclass. – ForrestforresterPost.new type: 'StickyPost
works. Strange that it doesn't work through the scope, since it also sets the type. – Forrestforrester