我有两个模型,通过另一个模型定义了多对多关系。 在这种情况下,用户属于许多组。 每个组可以有很多用户。 通过会员模型定义关系,会员模型也具有其成员资格的状态,即
user.rb
class User < ApplicationRecord has_many :memberships has_many :groups, through: :memberships endgroup.rb
class Group < ApplicationRecord has_many :memberships has_many :users, through: :memberships endmembership.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| %>有没有更好的方法来实现这一目标?
I have two models with a many-to-many relationship defined through another model. In this case A user belongs to many groups. And each group can have many users. There relationship is defined through a Membership model, which also has the status of their membership i.e.
user.rb
class User < ApplicationRecord has_many :memberships has_many :groups, through: :memberships endgroup.rb
class Group < ApplicationRecord has_many :memberships has_many :users, through: :memberships endmembership.rb
class Membership < ApplicationRecord belongs_to :user belongs_to :group enum status: [ :non_member, :pending, :member ] endWhen I create a new group, It always creates a membership for the user who created it. At a later date other users create memberships for a group.
Within one of my views, I want to show all groups that the current user belongs to. So I can do something like this:
<% @user.groups.each do |group| %> <p><%= group.name %> <% end %>I then want to show all the groups that a user does not belong to, so that they can request to join. I tried this, but it returns all records, even though my user is a member of one group.
<% Group.joins(:users).where.not(:users => { :id => current_user.id }).each do |group| %>Is there a better way to achieve this?
最满意答案
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试试这个......
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 endTry this instead...
更多推荐
发布评论