【问题标题】:Excluding results in has_many :through relation in Rails 3排除 has_many 中的结果:通过 Rails 3 中的关系
【发布时间】:2013-07-30 19:37:01
【问题描述】:

我正在尝试选择@current_user 不是其成员的组

我的模型相关部分如下:

class Group < ActiveRecord::Base
    belongs_to :user
    has_many :group_memberships 
    has_many :members, :class_name => "User", :through=>:group_memberships
 ...

class User < ActiveRecord::Base
    has_many :group_memberships, :foreign_key => 'member_id'
    has_many :groups, :through => :group_memberships
...

class GroupMembership < ActiveRecord::Base
    belongs_to :member, :class_name=>"User"  
    belongs_to :group
end

谢谢!

【问题讨论】:

    标签: ruby-on-rails-3 activerecord devise


    【解决方案1】:

    您可以尝试执行以下操作:

    @groups = Group.where("id NOT IN (?)", current_user.groups)
    

    更多信息可以在Active Record Query找到。

    【讨论】:

    • 啊..这实际上比以前的答案更实用..而且相当明显。谢谢。
    • 编辑:@groups = Group.where("id NOT IN (?)", current_user.groups) ...但是是的,谢谢!
    • 没问题。发现它也更有效率
    【解决方案2】:

    有这样的方法:

    def group_ids_not_a_member_of
      # get all group_ids and subtract out the ids that he is a member of
      Group.pluck('id') - current_user.groups.map(&:id) 
    end
    

    然后

    user.group_ids_not_a_member_of
    

    【讨论】:

    • 太棒了。似乎正在工作。你能告诉我一些关于 - 运算符的文档吗?
    • 基本上 Group.pluck('id') 将返回所有组 ID,第二部分是该当前用户的组 ID 的数组。由于它只是一个整数数组,您可以对其进行减法运算(即 Array1 - Array2)。 ruby-doc.org/core-2.0/Array.html#method-i-2D
    猜你喜欢
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2014-02-25
    相关资源
    最近更新 更多