I use Mongoid and Rails 3, and I have the following single table inheritance:
class Post
include Mongoid::Document
field :title, type: String
field :content, type: String
end
There is one model ‘Article’ inherited from Post:
class Article < Post
field :source, type: String
end
I am a novice to try STI. I learned that ‘one controller’ is a good design for base and inherited models. So I have the PostsController like this
class PostsController < ApplicationController
def index
@type = param[:type] # type is passed from the route.rb
@posts = Post.where(_type: @type)
...
So if @type is specified as ‘Article’, @posts will only contain the ‘Article’ type of posts. This work well in the articles view: only articles will be displayed, but not other kind of posts.
However, in the posts view, it will show both posts and articles.
I don’t want articles showing in my posts view — actually, I want only posts from the base model showing in the view. Is there a way to exclude items from inherited model in the base controller?
In other words, how can I find items only from the base model?
I just figured out I can use the following in the controller:
Is it the right way to go?