首页 > 解决方案 > 在 Rails 中创建用户家族

问题描述

我正在尝试对家庭中的用户进行分组。一个家庭可以有一个父母和多个成员,因此父母也被视为成员。

我已经尝试过这里提供的答案 ,用户和团队(rails)之间的关联和迁移 ,这里 有很多自加入 来尝试使其工作但没有运气

这是我所拥有的

class User < ActiveRecord::Base
# this defines the parent to members fine and you can get them
# only if you have the parent
  has_many :memberships, :class_name => 'Family', :foreign_key => 'user_id'
  has_many :family_members, :through => :memberships, :source => :registrar
# trying to define that user is also a member of family 
 belongs_to :registrar_family, :foreign_key => 'member_user_id'
end

class Family < ActiveRecord::Base
  belongs_to :user, :class_name => 'User', :foreign_key => "user_id"
  has_many :users, :class_name => 'User', :foreign_key => "id"
end

因此,如果我的用户 1 是父母并且有四个成员,我可以使用

user.family_members # to get family members for this parent 

但是我该怎么做才能让我也能从一个成员那里得到整个家庭

数据库示例

Users:
  id, name
 1, King
 2, Queen
 3, Prince
 4, Duaghter 
Users Family: 
 id,user_id, member_user_id
 1, 1, 2
 1, 1, 3 
 1, 1, 4

我该怎么说

user = User.find(4)
user.family.parent.members # which would return a family association 

完整的解决方案是(如果有人感兴趣):

class User < ActiveRecord::Base
  def family
    members = Family.where("user_id = ? OR member_user_id = ?", self.id, self.id)
    # if members is only 1 person then this person is a member only
    # then get all members from parent
    if members.count == 1
      members = members.first.parent.family
    end
    members
  end

  def family_count
    # if there is family then count is family + parent else 0
    family.count > 0 ? family.count + 1 : 0
  end

end

class Family < ActiveRecord::Base
  belongs_to :parent, :class_name => 'User', :foreign_key => "user_id"
end

标签: ruby-on-rails-5rails-activerecordmodel-associations

解决方案


也许你有你没有提到你为什么需要一Family门课的原因。但是对于一个简单的实现,您可以在User模型中完成所有操作:

class User < ApplicationRecord
  def is_parent?
    parent_id.nil?
  end

  def family
    User.where(id: id_of_parent).or(User.where(parent_id: id_of_parent))
  end

  private
  def id_of_parent
    is_parent? ? id : parent_id
  end
end

如果用户表包含

| id | first_name | parent_id |
| 1  | Fred       |  nil      |
| 2  | Wilma      |  1        |
| 3  | Pebbles    |  1        |
| 4  | Barney     |  1        |

然后:

> User.find(1).family.map(&:first_name) # -> [Fred,Wilma,Pebbles,Barney]
> User.find(2).family.map(&:first_name) # -> [Fred,Wilma,Pebbles,Barney]

如果愿意,您可以在 User 模型中添加自联接,但不会增加太多:

Class User < ActiveRecord::Base
  belongs_to :parent, class_name: 'User', foreign_key: :parent_id

  etc...

我意识到这与您的要求不完全一样,但它是否满足您的需求?


推荐阅读