我有一个Rails 3.2博客应用程序,根据公司及其所在地区向用户显示帖子.我还想显示用户是帖子作者的帖子,即使它是为其他公司或地区创建的(Post对象有一个区域和一个公司,以及User对象).
我在MySQL中用查询做了类似的事情:
SELECT * FROM Post WHERE approved = true AND hold = false AND
((company_id IN (null, 'user_company_id') AND region IN (null, 'user_region_id'))
OR author = 'user_id') ORDER BY published_date;
Run Code Online (Sandbox Code Playgroud)
我们现在使用Mongoid gem将应用程序迁移到MongoDB,这是我无法弄清楚的最后一个查询.到目前为止,我使用Origin和Selector的组合来调用文档:
@posts = Post.and(
{approved: true},
{hold_publish: false},
{"$or" => [
{"$and" => [{:company_id.in => [nil, @user.company.id]}, {:region_id.in => [nil, @user.region.id]}]},{user_id: @user.id}
]}).desc(:published_date)
Run Code Online (Sandbox Code Playgroud)
但是,这只会提取company_id和region_id为null或匹配users属性的帖子.