【问题标题】:Rails 5 search ActiveRecords with many to many relationship for matching fieldsRails 5搜索具有多对多关系的ActiveRecords以匹配字段
【发布时间】:2017-02-28 17:31:19
【问题描述】:

我有两个模型,它们具有通过另一个模型定义的多对多关系。在这种情况下,一个用户属于许多组。每个组可以有很多用户。 通过 Membership 模型定义关系,该模型也具有其成员身份,即

用户.rb

class User < ApplicationRecord
  has_many :memberships
  has_many :groups, through: :memberships
end

group.rb

class Group < ApplicationRecord
  has_many :memberships
  has_many :users, through: :memberships
end

membership.rb

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :group

  enum status: [ :non_member, :pending, :member ]
end

当我创建一个新组时,它总是为创建它的用户创建一个成员资格。稍后其他用户会为组创建成员资格。

在我的一个视图中,我想显示当前用户所属的所有组。所以我可以这样做:

<% @user.groups.each do |group| %>
   <p><%= group.name %>
<% end %>

然后我想显示用户不属于的所有组,以便他们可以请求加入。我试过这个,但它返回所有记录,即使我的用户是一个组的成员。

<% Group.joins(:users).where.not(:users => { :id => current_user.id }).each do |group| %>

有没有更好的方法来实现这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
    class User < ApplicationRecord
    
       has_many :memberships
       has_many :groups, through: :memberships
    
    
       def unjoined_groups
          Group.where.not(id: group_ids)
       end
    
       def unjoined_groups_by_membership_status(status)
          Group.includes(:memberships)
            .where.not(id: group_ids)
            .where(memberships: { status: status })
       end
    
    end
    

    试试这个吧……

    【讨论】:

    • 完美运行
    • 更复杂的是,是否可以根据会员状态添加条件?即..如果组和用户之间通过成员资格存在关联。但是会员状态是 non_member ?
    • @Dave 我已根据您的问题编辑了我的答案。我希望它符合您的需求。
    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2017-06-08
    • 1970-01-01
    相关资源
    最近更新 更多