Skip to content

Using orphan restrict

map7 edited this page Jun 7, 2011 · 2 revisions

Building upon the example from Railscast #262 I'm using orphan_strategy restrict so that people cannot remove messages which have replies to them.

I've added the orphan strategy to my model like so:

class Message < ActiveRecord::Base
  has_ancestry :orphan_strategy => :restrict
end

Then in my destroy method of the controller messages I've captured the exception and I display a message:

def destroy
  @message = Message.find(params[:id])

  begin
    @message.destroy
    redirect_to messages_url
  
  rescue Ancestry::AncestryException => exc
    @messages = Message.scoped
    flash[:alert] = "Message #{exc.message.downcase}"
    render :index
  end
end