Rails关联:更新关联参数(make admin / remove admin)

时间:2014-03-27 10:09:15

标签: ruby-on-rails ruby-on-rails-3 activerecord

所以我有一个User模型和一个Group模型,由于users模型,它有几个GroupUserAssociation。以下是我的关系的定义方式:

class Group < ActiveRecord::Base
  has_many :group_users, :class_name => 'GroupUserAssociation', :foreign_key => :group_id
  has_many :group_admins, :class_name => 'GroupUserAssociation', :foreign_key => :group_id, :conditions => ['level = 1']
  has_many :group_not_admins, :class_name => 'GroupUserAssociation', :foreign_key => :group_id, :conditions => ['level = 0']

  has_many :users, :through => :group_users, :source => :user
  has_many :admins, :through => :group_admins, :source => :user
  has_many :not_admins, :through => :group_not_admins, :source => :user
end

如果我想添加/删除用户到组,有一种优雅的方式来编写它(优雅,因为它不涉及GroupUserAssociation对象):

Group.first.users << User.first # Adds to group
Group.first.users.delete(User.first) # Removed from group

但如果我这样做

Group.first.admins << User.first
Group.first.admins.delete(User.first)

它也会删除关联(因此与第一行具有相同的效果)。

是否有一种优雅的方式(没有处理GroupUserAssociation对象来提升/降级管理员(=将GroupUserAssociation.level从1更新为0)?

我能做到

Group.first.users.delete(User.first) # Removed from group
Group.first.admins << User.first

但这意味着2次提交到DB并不是很好......

我在Rails 4中看到了一些很好的东西,但不幸的是我正在使用Rails 3.2 ......

由于

1 个答案:

答案 0 :(得分:0)

我们使用此代码执行此操作:

#config/routes.rb
resources :entries do
   post :category
   delete ":category_id", to: :category, as: "remove_category"
end

#Categories
def category
    entry = @entry = Entry.find(params[:entry_id])
    category = @category = Category.find(params[:category_id])

    #Actions
    entry.categories << category if request.post? && !entry.categories.include?(category)
    entry.categories.delete(category) if request.delete?

    #Return
    respond_to do |format|
        format.html { redirect_to collection_path }
        format.js
    end
end