HABTM关系查找所有记录,但不包括基于关联的记录 [英] HABTM relation find all records, excluding some based on association

查看:85
本文介绍了HABTM关系查找所有记录,但不包括基于关联的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过与此相关的一些类似SO帖子,但我一直在努力解决这个问题。

I've looked at some of the similar SO posts relating to this but I'm struggling to get my head around it.

我之间存在着一种害羞的关系项目和用户。我正在尝试查找特定用户不属于的所有项目,但我不知道怎么做。

I have a habtm relation between Projects and Users. I'm trying to find all the Projects that a particular user does not belong to but I don't know how.

我已经尝试过这种事情:

I've tried this sort of thing:

Project.where('project_id != ?', user.id)

但这显然也是错误的。

我正在使用rails 3.2.x

I'm using rails 3.2.x

与该提及的示波器有关的许多答案,但我以前从未见过(我对Rails还是很陌生)。

Many of the answers relating to this mention scopes but I haven't come across them before (I'm still very new to Rails).

我刚发现使用一个答案提示发布: Project.where('id not in(?)',user.projects)

I just found this post with one answer suggesting: Project.where('id not in (?)', user.projects)

这似乎可行,除了 user.projects 为空时。我正在尝试 Project.where('id not in(?)',(d.projects.empty??'',d.projects))
正如JosephCastro的答案注释线程中所建议的那样,但是它在第二个 d.projects 中给了我一个语法错误。

which seems to work, except when user.projects is empty. I'm trying Project.where('id not in (?)', (d.projects.empty? ? '', d.projects)) as is suggested in JosephCastro's answer comment thread but it's giving me a syntax error on the second d.projects.

编辑

与用户相关的项目模型摘要

Project model snippet that relates to Users

class Project < ActiveRecord::Base
  attr_accessible ...
  has_and_belongs_to_many :users, :before_add => :validates_unique

,然后

class User < ActiveRecord::Base
  attr_accessible ...
  has_and_belongs_to_many :projects


推荐答案

您可以像这样在您的项目模型中放置一个范围:

You can place a scope in your Project model like so:

scope :not_belonging_to, lambda {|user| joins(:projects_users).where('projects_users.user_id <> ?', user.id) }}

这假定您的联接表名称与 HABTM 关联的rails约定

This assumes your join table name matches rails convention for HABTM associations

要获得的项目用户不属于用户,请首先找到您的用户,然后将其传递给范围,例如:

To then get projects that a user doesn't belong to, first find your user, then pass them to the scope like so:

@user = User.find(params[:id]) # example
@unowned_projects = Project.not_belonging_to(@user)

反思时,该范围将不起作用,因为它将发现拥有多个开发人员的项目,如果其中一个是您的人。

On reflection, that scope won't work as it will find projects that have more than one developer, if one of those is your guy.

相反,请使用以下内容:

Instead, use the following:

scope :not_belonging_to, lambda {|user| where('id NOT IN (?)', user.projects.empty? ? '' : user.projects) }

这篇关于HABTM关系查找所有记录,但不包括基于关联的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆