gpt4 book ai didi

mysql - Rails - 在组、用户、所有者、成员协会方面遇到困难

转载 作者:行者123 更新时间:2023-12-02 04:12:22 29 4
gpt4 key购买 nike

我到处都找过了,但一直找不到我要找的东西。我知道我需要什么,但无法将 2 和 2 放在一起。

  • 我需要允许用户创建群组并允许其他用户加入群组。
  • 任何用户都可以创建群组。
  • 任何用户都可以发送加入另一个群组的请求。
  • 一名用户只能创建一个组,但可以属于多个组。
  • 群组的创建者是群组的所有者。
  • 所有成员和所有者都是普通用户,没有特殊权限。
  • 群组创建者/所有者可以添加/删除其他群组成员。

这段代码不正确,但这就是想法:

class Group < ActiveRecord::Base
has_one :owner, :class_name => "user"
has_many :members, :class_name => "user"
end

class User < ActiveRecord::Base
belongs_to :groups
has_one :group, :class_name "user"
end

我相信我需要一个 has_many :through 关联,但不确定如何实现它。如何构建模型/ Controller /迁移以表示上述参数内的关联?

最佳答案

我建议也使用连接表,如下所示:

class Membership < ActiveRecord::Base
belongs_to :group
belongs_to :user
end

class Group < ActiveRecord::Base
belongs_to :owner, class_name: "User"
has_many :members, through: :memberships, source: :user
has_many :memberships
end

class User < ActiveRecord::Base
has_one :owned_group, foreign_key: "owner_id", class_name: "Group"
has_many :groups, through: :memberships
has_many :memberships
end

迁移如下:

class CreateMemberships < ActiveRecord::Migration
def change
create_table :memberships do |t|
t.references :user
t.references :group

t.timestamps null: false
end
end
end

class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.timestamps null: false
end
end
end

class CreateGroups < ActiveRecord::Migration
def change
create_table :groups do |t|
t.references :owner

t.timestamps null: false
end
end
end

schema design

关于mysql - Rails - 在组、用户、所有者、成员协会方面遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881547/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com