【发布时间】:2017-03-01 19:32:29
【问题描述】:
我有 3 个模型; User、Group 和 GroupMap。
用户可以有多个组,组可以有多个用户。这是 n-m 关系,它是通过 GroupMap 完成的。 GroupMap 也有状态和类型,所以我也需要这个模型。这是第一个关系。
一个组只能有一个所有者,即用户。这是 1-n 关系。
user.rb
class User < ApplicationRecord
has_many :group_maps
has_many :groups, :through => :group_maps
group.rb
class Group < ApplicationRecord
belongs_to :user
has_many :group_maps
has_many :users, :through => :group_maps
group_map.rb
class GroupMap < ApplicationRecord
belongs_to :group
belongs_to :user
groups_controller.rb
class GroupsController < ApplicationController
def new
@group = Group.new
end
def create
@group = current_user.groups.create(group_params)
if @group.save
redirect_to root_path
else
render 'new'
end
end
虽然我可以使用此代码创建组,但这里有 2 个问题;
- 在 Group 模型中存储所有者的 user_id 始终为零,尽管在 GroupMap 模型中它正确设置了 user_id。
- 在第 1 步中,也可以在 GroupMap 中看到所有者,因为它也是该组的成员,但其状态始终为 nil。有 3 种状态(等待、接受、拒绝)。在这种情况下,当所有者创建该组时,它在该组中的状态也必须被接受。
日志
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "groups" ("name") VALUES (?) [["name", "Football lovers"]]
SQL (0.5ms) INSERT INTO "group_maps" ("group_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["group_id", 8], ["user_id", 4], ["created_at", 2017-03-01 19:03:55 UTC], ["updated_at", 2017-03-01 19:03:55 UTC]]
【问题讨论】:
标签: ruby-on-rails ruby relationship