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

标签 mysql ruby-on-rails ruby-on-rails-4 activerecord associations

我到处都找过了,但一直找不到我要找的东西。我知道我需要什么,但无法将 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/

相关文章:

ruby-on-rails-4 - Rails omniauth-saml + devise + ADFS 问题

mysql - 如何计算一组单词以任意顺序出现在列中的次数?

javascript - 无法读取未定义的属性 'Api' 来加载响应式数据表.js

php - 如何将这些数据分组到数组中?

ruby-on-rails - 在 mongoid 中不区分大小写搜索单词

ruby-on-rails - Rails 中的表单对象

ruby-on-rails - Rolify 动态调用未运行或无法被 heroku 识别

ruby - Controller#index中的NameError未初始化的常量

mysql - 我的查询有什么问题

mysql - 根据特定属性选择属性