【问题标题】:Rails User Groups - Set Group Owner In Another ModelRails 用户组 - 在另一个模型中设置组所有者
【发布时间】:2015-03-23 05:53:50
【问题描述】:

我的应用程序中有用户创建的组。我对如何将创建组的用户设置为所有者感到困惑。我希望能够有多个所有者,所以这是一种“多方通行”的关系。我可以创建/编辑/删除一个组。

所以我的问题是如何在创建组时将当前的 user_id 和 group_id 插入到 group_owners 表中?

这是我目前所拥有的:

用户模型

class User < ActiveRecord::Base

  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :confirmable

  has_many :group_owners
  has_many :user_groups, through: :group_owners

end

组模型

class UserGroup < ActiveRecord::Base

   has_many :goup_owners
   has_many :users, through: :groups_owners

   validates :name, presence: true, length: {minimum: 5}
   validates :visibility, presence: true, length: {minimum: 5}

   VISIBILITY_TYPES = ["Public", "Private"]

end

组所有者模型

class GroupOwner < ActiveRecord::Base

   belongs_to :user
   belongs_to :user_group

end

用户组控制器 - 创建操作

def create
   @usergroup = UserGroup.new(usergroup_params)
   if @usergroup.save
     redirect_to user_groups_path
   else
     render 'new'
   end
end

我认为用户组创建方法中需要进行一些操作,但我不确定是什么。

感谢您提供的任何帮助。

【问题讨论】:

  • 你有什么问题?
  • 如何在创建用户组时,将当前用户 id 和组 id 添加到组所有者表中?

标签: ruby-on-rails has-many-through


【解决方案1】:

你应该像这样创建用户组

def create
 @usergroup = current_user.user_groups.build(usergroup_params)
 if @usergroup.save
   redirect_to user_groups_path
 else
  render 'new'
 end
end

这样,用户组将使用当前用户 ID 和组 ID 创建到组所有者表中。

【讨论】:

  • 谢谢,但是这似乎并没有在 group_owners 表中创建记录。没有错误,但不起作用。
【解决方案2】:

在您的 UserGroup 模型中,为所有者设置一个布尔值。

create_table |t|
  t.references :user
  t.references :group
  t.boolean :owner
end

class UserGroup < ActiveRecord::Base
  belongs_to :user
  belongs_to :owner

  scope :groups, ->(*g) {where(group_id: g.flatten.compact.uniq)}
  scope :users, ->(*u) { where(user_id: u.flatten.compact.uniq)}
  scope :owners, ->{where owner:true}
end

class User < ActiveRecord::Base
  has_many :user_groups, dependent: :destroy, inverse_of: user
  has_many :groups, through: :user_groups

  def owned_groups
    groups.merge(UserGroup.owners)
  end
end

【讨论】:

    【解决方案3】:

    对用户组控制器创建方法的以下更改解决了我的问题。

    def create
        @user_group = current_user.user_groups.build(usergroup_params)
        if @user_group.save
          @user_group.users << current_user
          redirect_to user_groups_path
        else
          render 'new'
        end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多