Sterling Duchess
Sterling Duchess

Reputation: 2080

Before_destroy filter now calling given method

My User's have one Group assigned each. If admin removes they group they are in i need to move them down to most basic gorup "Member" that cannot be removed.

Now i know that the method works and routing and controller however because at first i called the method moveUsers from controller in order:

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

However i want to seperate this and keep controller minimalistic, the: Rails3 way?

Controller method:

  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

Model:

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

Upvotes: 0

Views: 241

Answers (1)

vdaubry
vdaubry

Reputation: 11439

The delete method ignores callback methods

You need to use group.destroy in order to fire the before_destroy callback

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

Upvotes: 2

Related Questions