Inheritance 在Mongoid中,如何在基本控制器中排除继承的模型对象?
我使用Mongoid和Rails 3,并具有以下单表继承:Inheritance 在Mongoid中,如何在基本控制器中排除继承的模型对象?,inheritance,mongoid,Inheritance,Mongoid,我使用Mongoid和Rails 3,并具有以下单表继承: class Post include Mongoid::Document field :title, type: String field :content, type: String end 从Post继承了一个模型“文章”: class Article < Post field :source, type: String end class文章
class Post
include Mongoid::Document
field :title, type: String
field :content, type: String
end
从Post继承了一个模型“文章”:
class Article < Post
field :source, type: String
end
class文章
我是尝试STI的新手。我了解到“一个控制器”对于基础模型和继承模型来说是一个很好的设计。所以我有一个这样的PostsController
class PostsController < ApplicationController
def index
@type = param[:type] # type is passed from the route.rb
@posts = Post.where(_type: @type)
...
class PostsController
因此,如果@type被指定为'Article',@posts将只包含'Article'类型的posts。这在文章视图中很有效:只显示文章,而不显示其他类型的文章
然而,在posts视图中,它将同时显示post和article
我不希望文章显示在我的posts视图中——事实上,我只希望基本模型中的文章显示在视图中。是否有方法从基本控制器中的继承模型中排除项
换句话说,我如何才能仅从基本模型中找到项目?我刚刚发现我可以在控制器中使用以下功能:
@post = Post.where(_type: "Post")
这是正确的方式吗?是的,否则它将返回所有内容。您可以尝试添加一个默认的作用域,其中(_type:“Post”)用于Post,并查看它是否有帮助。