Before_destroy过滤器现在调用给定的方法

时间:2013-03-10 21:26:28

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

我的用户每个都分配了一个组。如果管理员删除了他们组,我需要将他们移动到无法删除的大多数基本gorup“会员”。

现在我知道该方法有效,路由和控制器但是因为我首先从控制器调用了方法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

1 个答案:

答案 0 :(得分:2)

delete方法忽略回调方法

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

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