2017-04-04 125 views
2

我正在努力寻找适合于简单任务的解决方案。基本上我有一个类别模型其中有很多职位属于类别Rails查询关联的模型范围

我显示类别作为搜索表单的一部分以及其他地方的一部分,不想显示没有关联的职位的类别。这似乎毫无意义。

我设法通过向我的类别模型添加以下方法来解决此问题。

# Check if Category has associated results 
def self.with_results 
    includes(:posts).where.not(posts: { id: nil }) 
end 

工作正常,允许我筛选没有结果的类别。稍微混乱的一点是当我尝试使用示波器时。

我的文章有几个范围,如frontend_visible,它决定了它是否应该从前端(非管理员)访问。

scope :frontend_visible, -> { where(:state => ['approved', 'changes_pending_approval']) } 

同样,我还有其他范围可以取消标记为专用内容(仅限会员)的帖子。

我最初的解决方案的问题是,包含未获批准帖子的类别将不会显示,同样非成员将无法查看标记为私人的帖子,尽管该类别仍将显示。

理想的解决办法是这样的:

获取那些相关联的帖子,如果相关联的帖子不可见的前端,无视类别的所有类别。如果current_user无法访问私人内容并且所有相关帖子都被标记为私人,则忽略类别。

我有范围,但我不确定如何使用它们从关联的模型。这可能吗?

+0

所以,你想有是前端可见帖子所有类别? Category.includes(:posts).where(frontend_visible:true).where.not(posts:{id:nil})...如果您使用的是Rails5,则无需加载关联的表只是查询它是否有相关记录:Category.where(frontend_visible:true).left_outer_joins(:posts).where(posts:{id:nil}) – bkunzi01

+0

[here](http://guides.rubyonrails.org /active_record_querying.html#scopes)你可以找到一个解决方案...例如合并范围或范围范围... – rfellons

+0

@ bkunzi01谢谢你,但是你的例子都不适合我。我得到以下错误:PG :: UndefinedColumn:错误:列类别。frontend_visible不存在 – Torrm

回答

1

据我所知,您需要选择具有用户可见的帖子的类别。对于您需要做两件事情:用户的角色和岗位的可见范围

  • 选择类别的职位由用户可见之间

    1. 制作映射。在你的情况下,更容易在两个查询中选择这些类别,而无需连接。

    试试这个代码:

    class Category < ApplicationRecord 
        has_many :posts 
    
        scope :with_posts_for_user, -> (user) do 
        where(id: Post.categories_for_user(user)) 
        end 
    end 
    
    class Post < ApplicationRecord 
        belongs_to :category 
    
        scope :frontend_visible, -> { where(:state => ['approved', 'changes_pending_approval']) } 
        scope :member_visible, -> { where(:state => ['approved', 'changes_pending_approval', 'private']) } 
    
        scope :categories_for_user, -> (user) do 
        (user.member? ? member_visible : frontend_visible).distinct.pluck(:category_id) 
        end 
    end 
    
  • +0

    您的解决方案非常出色,感谢您花时间分享此内容! – Torrm