【问题标题】:Different Relationships with the same model同一模型的不同关系
【发布时间】:2017-03-01 19:32:29
【问题描述】:

我有 3 个模型; UserGroupGroupMap

用户可以有多个组,组可以有多个用户。这是 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 个问题;

  1. 在 Group 模型中存储所有者的 user_id 始终为零,尽管在 GroupMap 模型中它正确设置了 user_id。
  2. 在第 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


    【解决方案1】:

    组/用户所有者关系是独立于GroupMap 关系的关系。您需要单独指定。

      def create
        @group = current_user.groups.create(group_params)
        @group.user = current_user
    
        if @group.save
          group_map = @group.group_maps.first
          group_map.status = 'accepted'
          group_map.save
          redirect_to root_path
        else
          render 'new'
        end
      end
    

    【讨论】:

    • 谢谢,这适用于问题 1。关于问题 2,我该怎么办?
    • 我已经编辑了我的答案,以展示如何将此组的 group_map 状态设置为“已接受”
    猜你喜欢
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多