0

我的用户每个人都分配了一个组。如果管理员删除了他们所在的组,我需要将它们移至无法删除的最基本的组“成员”。

现在我知道该方法有效并且路由和控制器但是因为起初我按顺序从控制器调用方法 moveUsers:

user = User.find(id)  
user.moveUsers
user.delete

但是,我想将其分开并保持控制器的简约,即:Rails3 方式?

控制器方法:

  def destroy
    group = Group.find(params[:id])

    if group.delete
      redirect_to groups_url, :notice => "Group deleted."
    else
      redirect_to :back, :notice => "Cannot delete group."
    end

  end

模型:

class Group < ActiveRecord::Base
    before_destroy :moveUsers

    validates :title, :presence => :true, :uniqueness => true
    has_many :user

    # Get the number of users associated with the group & title
    def getUserCount
        return User.where(:group_id => self.id).length
    end

    # If group is deleted move all of its users
    # to core group: Members (id = 1)
    private
    def moveUsers
        users = User.where(:group_id => self.id)

        users.each do |user|
            user.group_id = 1
            user.save
        end
    end
end
4

1 回答 1

2

删除方法忽略回调方法

您需要使用 group.destroy 来触发 before_destroy 回调

http://guides.rubyonrails.org/active_record_validations_callbacks.html#skipping-callbacks

于 2013-03-10T21:30:18.953 回答